面试集锦--构造函数初始化顺序问题
#include <iostream>using namespace std;class OBJ1{public: OBJ1(){ cout <<"OBJ1\n"; }};class OBJ2{public: OBJ2(){ cout <<"OBJ2\n"; }};class Base1{public: Base1(){ cout <<"Base1\n"; }};class Base2{public: Base2(){ cout <<"Base2\n"; }};class Base3{public: Base3(){ cout <<"Base3\n"; }};class Base4{public: Base4(){ cout <<"Base4\n"; }};class Derived :public Base1, virtual public Base2, public Base3, virtual public Base4{public: Derived() :Base4(), Base3(), Base2(), Base1(), obj2(), obj1() { cout <<"Derived ok.\n"; }protected: OBJ1 obj1; OBJ2 obj2;};int main(){ Derived aa; cout <<"This is ok.\n"; int i; cin >> i; return 0;}结果:Base2Base4Base1Base3OBJ1OBJ2Derived ok.This is ok.
分析以上输出结果可以得出以下结论:在被继承的基类中,虚基类优先级最高,其次是普通的基类,然后是本类的成员函数按照顺序构造。在所有的虚基类中按照被继承的顺序对各个类中成员进行初始化。同样在所有的普通基类中按照被继承的顺序对各个类中成员进行初始化。