だから、私はクラスの車を持っています:
car.h
#ifndef CAR_H
#define CAR_H
#include <iostream>
#include <string.h>
#include "car.cpp"
// Car class with its attributes
class Car {
public:
std::string brand;
std::string model;
int year;
// Constructor
Car(int year, std::string model, std::string brand);
};
#endif
そして、別の.cppファイルのクラスの外にクラスコンストラクター定義を作成したかったのです。
car.cpp
#include <string.h>
Car::Car(int year, std::string model, std::string brand)
{
this->brand = brand;
this->model = model;
this->year = year;
}
コンパイルしようとしましたが、このエラーが発生しました:
car.cpp:3:1: error: ‘Car’ does not name a type
なぜそれが起こったのか、そしてそれを修正する方法は?
私のmain.cpp:
#include <iostream>
#include "car.h"
using namespace std;
int main() {
// Create an object of Car
Car carObj1 = Car(1992, "model X", "Brand1");
// Create another object of Car
Car carObj2 = Car(2003, "model Y", "Brand2");
// Print attribute values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
インクルードを間違った方法で入手しました。car.cppは#include "car.h"
その逆であってはなりません。
またの正しいヘッダファイルがstd::string
あり<string>
ません<string.h>
また、メンバーの初期化は、割り当てではなくイニシャライザーリストを使用して行う方が適切です。
Car::Car(int year, std::string model, std::string brand) :
brand(brand), model(model), year(year)
{
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加