C++继承 类的构造顺序

#include <iostream>
using namespace std;
class Base1 {//基类Base1,构造函数有参数
public:
    Base1(int i) 
  { cout << "Constructing Base1 " << i << endl; }
};

class Base2 {//基类Base2,构造函数有参数
public:
    Base2(int j) 
  { cout << "Constructing Base2 " << j << endl; }
};

class Base3 {//基类Base3,构造函数无参数
public:
    Base3() 
  { cout << "Constructing Base3 *" << 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;
}
// Constructing Base2 2
// Constructing Base1 1
// Constructing Base3 *
// Constructing Base1 3
// Constructing Base2 4
// Constructing Base3 *

当多重继承时,先按顺序调用父类构造器,再按顺序调用组合成员构造器。

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;
};

可以看出,Derived类先是继承了Base2Base1Base3 ,所以得先构造以上三个继承类的基类,顺序为Base2Base1Base3 ,和继承数据一致。初始化完了父类对象后,则是初始化组合成员对象。按照成员声明来初始化

private:
    Base1 member1;
    Base2 member2;
    Base3 member3;
};

另外一提:析构函数的调用顺序和构造是反的。如先析构父类对象,自右向左。再析构组合对象,自下向上。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值