如何在另一个文件中定义类的构造函数?

4

因此,我有一个名为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;
}

[OT]: #include <string.h> -> #include <string> [OT]:#include <string.h> -> #include <string> - Jarod42
car.cpp 需要 #include "car.h",以便编译器在定义构造函数之前能够看到 Car 的定义。如果编译器无法看到类定义,则无法定义(也称为实现)类的任何成员函数。 - Peter
2个回答

7

你选错了头文件的顺序。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)
{
}

同时,在car.h中不需要包含car.cpp - asmmo

4
#include "car.cpp"

这是错误的。永远不要包含源文件。

‘Car’ does not name a type

Why it happened

car.cpp 试图使用未定义的类 Car

如何修复此问题?

在 car.cpp 中添加 #include "car.h" 来定义 Car,以便在使用之前进行定义。然后从 car.h 中删除 #include "car.cpp",以避免递归包含会导致正确的包含顺序错误。


好的,谢谢!现在它可以工作了。我应该立即向StackOverflow寻求帮助,因为我已经处理这个错误一个小时了。但最终,我还是学到了一些东西。 - rebix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接