我需要创建一个包含 3 个集合和 3 个获取以及构造函数的程序。但是,当我创建默认构造函数时,它给了我一个错误,指出行中的“,”之前需要有一个“)”
#include <string>
class Vehicle
{
public:
Vehicle(std::string vehicleType, int numberOfDoors, int maxSpeed)
: type{vehicleType}, number{numberOfDoors}, speed{maxSpeed}{}
void setType(std::string vehicleType) {
type = vehicleType;}
void setNumber(int numberOfDoors){
number = numberOfDoors;}
void setSpeed(int maxSpeed) {
speed = maxSpeed;}
Vehicle(string, int, int);
~Vehicle();
Vehicle();
std::string getType() const {return type;}
int getNumber() const {return number;}
int getSpeed() const {return speed;}
private:
std::string type;
int number;
int speed;
};
谁能告诉我哪里出了问题?
最佳答案
您已经在类的开头定义了三参数构造函数,您在其中使用成员初始化列表来初始化类 Vehicle
的成员变量。因此您无需在下面再次声明:
Vehicle(string, int, int);
如果删除此行,您的代码将编译。参见 here
当你实例化你的类时,你需要提供三个参数,一个 string
和两个 int
此外,如果您想要一个默认构造函数,您可以将以下行添加到您的类中。
Vehicle():type(), number(0), speed(0){}
然后您应该能够在没有任何参数和用户 Setter 函数的情况下实例化您的 Vehicle
类来为此类对象的成员变量设置值。
也可以删除未定义的析构函数或以这种方式定义析构函数:
~Vehicle(){ type.clear();}
参见 here
关于c++ - 默认构造函数 C++ 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42240470/