示例代码:
#include <iostream>
using namespace std;
class Base1 {
public:
Base1(int i) {
cout << "Base1's construct is called " << i << endl;
}
};
class Base2 {
public:
Base2(int j) {
cout << "Base2's construct is called " << j << endl;
}
};
class Base3 {
public:
Base3() {
cout << "Base3's construct is called" << endl;
}
};
class Derived : public Base2, public Base1, public Base3 {
public:
Derived(int a, int b, int c, int d) : Base1(a), member2(d), member1(c),
Base2(b) {}
private:
Base1 member1;
Base2 member2;
Base3 member3;
};
int main() {
Derived obj(1, 2, 3, 4);
return 0;
}
运行结果:
多继承的派生类构造函数执行顺序:
1.调用基类构造函数——按照继承的顺序依次执行,2和1
2.对初始化列表中的成员初始化——按照其在类中定义的顺序进行初始化,对象成员初始化时自动调用其所属的构造函数
member1和member2自动调用Base1和Base2的构造函数