gpt4 book ai didi

C++ 继承 : Calling constructor w/args

转载 作者:行者123 更新时间:2023-11-28 03:06:45 25 4
gpt4 key购买 nike

我试图在子类的带参数的构造函数中调用带参数的父类的构造函数,但我收到编译器错误“expected primary expression before ...”。这是我的:

class Ship {
private:
string shipName;
int yearBuilt;
public:
Ship();
Ship(string name, int year);
};
class CruiseShip: public Ship {
private:
int maxPeople;
public:
CruiseShip()
: Ship() {
maxPeople = 100;
}
CruiseShip(int m)
: Ship(string name, int year) {
maxPeople = m;
}
};
Ship::Ship() {
shipName = "Generic";
yearBuilt = 1900;
}
Ship::Ship(string name, int year) {
shipName = name;
yearBuilt = year;
}

这是我遇到问题的特定代码:

    CruiseShip(int m)
: Ship(string name, int year) {
maxPeople = m;
}

我的目标是能够创建一个对象,CruiseShip c1,它有 3 个参数来设置名称、年份和最大人数。我一直在网上阅读,它告诉我这应该没问题,但我显然做错了什么。如果有任何意见,我将不胜感激!

最佳答案

您需要像这样将参数传递给父类构造函数:

CruiseShip(int m, string name, int year): Ship(name, year), maxPeople(m) {}

更好的是,你应该在初始化列表中将 maxPeople 设置为 m

关于C++ 继承 : Calling constructor w/args,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19484167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com