C++ - 基类的构造函数使用参数的构造函数

use*_*279 5 c++ inheritance

我有一个继承Vehicle类的Car类.Car和Vehicle类都接受参数"wheels".根据我对继承如何工作的理解,对象Car将分两个阶段构建:Vehicle首先通过调用其构造函数来构造,然后是Car,它也将调用它的构造函数.我的问题是当Vehicle的构造函数使用它的参数时,我将如何编写Car的构造函数?

class Vehicle {
public:
    Vehicle(int wheels);
};

class Car {
public:
    Car(int wheels): Vehicle(wheels);
};
Run Code Online (Sandbox Code Playgroud)

per*_*eal 11

你需要从Vehicle继承:

头文件:

class Car: public Vehicle {
public:
    Car(int wheels);
};
Run Code Online (Sandbox Code Playgroud)

Cpp文件:

Car::Car(int wheels): Vehicle(wheels) {
}
Run Code Online (Sandbox Code Playgroud)


Mor*_*itz 6

您将轮子传递给 Vehicle 构造函数,然后在 Car 构造函数中处理其他参数。

class Car : public Vehicle {
public:
    Car(int otherParam, int wheels);
};

Car::Car(int otherParam, int wheels) : Vehicle(wheels) {
    //do something with other params here
}
Run Code Online (Sandbox Code Playgroud)

当然,您可以有多个其他参数,它们不需要是整数;)

编辑:在我的初始示例中,我也忘记了从车辆继承,感谢 perreal 指出这一点。