0

I'm trying to invoke my parent class's constructor that has arguments, in my child class's constructor with arguments, but I get a compiler error "expected primary expression before ...". This is what I have:

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;
}

And this is the specific piece of code I'm having trouble with:

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

My goal is to be able to create an object, CruiseShip c1 with 3 arguments that set the name,year, & max people. I've been reading online and it tells me that this should be ok, but I'm obviously doing something wrong. I'd appreciate any input, thanks!

4

1 回答 1

2

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

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

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

于 2013-10-20T23:40:08.753 回答