C++多重继承,菱形继承中构造函数的调用顺序
C++中多重继承不免会出现钻石继承,也就是继承类的两个基类同时又是同一个基类的继承类,当创建一个对象的时候,他们是按照什么样的顺序调用构造函数的呢。
如果不进行虚拟继承:
class Base { public: Base() { cout<<"Base默认构造函数调用"<<endl; } Base(int i) { cout<<"Base参数构造函数调用"<<endl; cout<<i<<endl; } virtual ~Base(){} }; class Base1: public Base{ public: Base1(int i,int j=0):Base(j){ cout<<"Base1参数构造函数调用"<<endl; cout<<i<<endl; } virtual ~Base1(){} }; class Base2: public Base{ public: Base2(int i):Base(i){ cout<<"Base2参数构造函数调用"<<endl; cout<<i<<endl; } virtual ~Base2(){} }; class Drived:public Base1,public Base2{ public: Drived(int a,int b,int c,int d):Base1(a),Base2(b){ } virtual ~Drived(){} };
新建对象的运行结果:
虚拟继承(虚拟继承中Base1 Base2 中对Base的构造函数调用不再起作用,Base构造函数的调用由derived类直接负责,若Drived不明确指出,则调用默认无参数的构造函数):
class Base { public: Base() { cout<<"Base默认构造函数调用"<<endl; } Base(int i) { cout<<"Base参数构造函数调用"<<endl; cout<<i<<endl; } virtual ~Base(){} }; class Base1: virtual public Base{ public: Base1(int i,int j=0):Base(j){ cout<<"Base1参数构造函数调用"<<endl; cout<<i<<endl; } virtual ~Base1(){} }; class Base2: virtual public Base{ public: Base2(int i):Base(i){ cout<<"Base2参数构造函数调用"<<endl; cout<<i<<endl; } virtual ~Base2(){} }; class Drived:public Base1,public Base2{ public: Drived(int a,int b,int c,int d):Base1(a),Base2(b){ } virtual ~Drived(){} };
新对象的运行结果:
如果Drived类中有Base1 Base2 类型的成员函数:
class Drived:public Base1,public Base2{ public: Base1 mem1; Base2 mem2; Drived(int a,int b,int c,int d):Base1(a),Base2(b),mem1(c),mem2(d){ } virtual ~Drived(){} };
则新对象的运行结果如图:
如果在Derived类中指定Base的构造函数:
class Drived:public Base1,public Base2{ public: Base1 mem1; Base2 mem2; Drived(int a,int b,int c,int d):Base1(a),Base2(b),Base(a),mem1(c),mem2(d){ } virtual ~Drived(){} };
则运行结果如图所示:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。