重载构造函数抛出重定义错误



我有一个赋值,要求我为c++中的类(Car)编写重载构造函数。我一直得到一个重新定义错误,但不能确定是什么原因造成的。我觉得这可能与两个独立文件(Car.h, Car.cpp)之间的代码分离有关,但我不确定。

Car.h中的类:

class Car {
public:
Car(){}; 
Car(string userMake, string userModel, double userPrice){};
string getMake();
string getModel();
double getPrice();

private:
string make;
string model;
double price;
};
下面是Car.cpp中抛出错误的构造函数:
Car::Car () {
make = "DeLorean";
model = "Alpha5";
price = 145000;
}
Car::Car (string userMake, string userModel, double userPrice) {
make = userMake;
model = userModel;
price = userPrice;
}

下面是编译错误:

Car.cpp:6:1: error: redefinition of ‘Car::Car()’
6 | Car::Car () {
| ^~~
In file included from Car.cpp:1:
Car.h:10:9: note: ‘Car::Car()’ previously defined here
10 |         Car(){};
|         ^~~
Car.cpp:14:1: error: redefinition of ‘Car::Car(std::string, std::string, double)’
14 | Car::Car (string initMake, string initModel, double initPrice) {
| ^~~
In file included from Car.cpp:1:
Car.h:11:9: note: ‘Car::Car(std::string, std::string, double)’ previously defined here
11 |         Car(string initMake, string initModel, double initPrice){};
|         ^~~

我觉得我一直在非常密切地遵循讲座和课本活动中给出的例子,所以我不知道如何排除故障。

Car(){}; 
Car(string userMake, string userModel, double userPrice){};

这些定义了构造函数的主体,而不仅仅是声明了它们的签名。因为看起来您想要在.cpp文件中实现类之外的构造函数(这是一个很好的做法),所以只需删除大括号。原型没有函数体,即使是空函数体。

Car(); 
Car(string userMake, string userModel, double userPrice);

最新更新