我是在空闲时间开始学习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对象不能?
非常感谢你的帮助!!
发布于 2021-04-15 11:00:16
您缺少默认构造函数。放在这里:
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) {
}比你的方式更有效
发布于 2021-04-15 11:00:35
而不是这样:
Car myObjMSRP;您需要传递构造函数参数:
Car myObjMSRP("Tesla", "Roadster", 2022);https://stackoverflow.com/questions/67101648
复制相似问题