C++错误:调用'Car::Car()'没有匹配函数



我在空闲时间开始学习C++,在学习封装时遇到了一个错误。以下是代码(这是对W3Schools上解释的内容的轻微修改(:

#include <iostream>
using namespace std;
class Car {                          // The class
private:                         // Access specifier to prevent outsiders from viewing (ENCAPSULATION)
int theMSRP;                // Private attribute of the car (we don't want random person seeing car price)
public:
string brand;               // Attribute
string model;               // Attribute
int year;                   // Attribute
Car(string x, string y, int z){ // Constructor with parameters
brand = x;
model = y;
year = z;
}
// Private access specifier SETTER
void setMSRP(int m){
theMSRP = m;
}
// Private access specifier GETTER
int getMSRP(){
return theMSRP;
}
};
int main(){
// Create Car objects and call the constructor with different values
Car myObjMSRP;
myObjMSRP.setMSRP(100000);
Car carObj1("Mercedes Benz", "G-Wagon", 2021);
// Print the values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << " n";
cout << myObjMSRP.getMSRP();
return 0;
}

错误消息返回错误:调用"Car::Car(("没有匹配的函数。我有点困惑,因为另一个对象可以与Car类一起使用,但myObjMSRP对象不能?

非常感谢你的帮助!!

而不是这个:

Car myObjMSRP;

您需要传递构造函数参数:

Car myObjMSRP("Tesla", "Roadster", 2022);

您缺少默认构造函数。放这个:

Car () {
make = "";
model = "";
year = "";
std::cout << "Hell got loose!!!";
}

您将从这条线路呼叫

Car myObjMSRP;

或者你可以有

Car myObjMSRP ("Nissan", "Q5", 2011);

尽管有一个建议,但要了解构造函数上的初始值设定项列表:

Car (string x, string y, string z) : make(x), model(y), year(z) {
}

比你的方式更有效

最新更新