因此,我有一个名为Car的类:
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;
}
#include <string.h>
->#include <string>
[OT]:#include <string.h>
->#include <string>
- Jarod42car.cpp
需要#include "car.h"
,以便编译器在定义构造函数之前能够看到Car
的定义。如果编译器无法看到类定义,则无法定义(也称为实现)类的任何成员函数。 - Peter