简体   繁体   中英

C++ Inheritance: Calling constructor w/ args

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!

You need to pass parameters to parent class constructor like this:

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

Better, you should set maxPeople to m in the initializer list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM