多继承且有内嵌对象时构造函数的调用顺序

1、调用基类构造函数,调用顺序按照他们被继承时声明的顺序(从左到右)

2、调用成员对象的构造函数,调用顺序按照它们在类中声明的顺序

3、最后调用本类的构造函数

#include <iostream>
using namespace std;
class B1    //基类B1,构造函数有参数
{public:
    B1(int i) {cout<<"constructing B1 "<<i<<endl;}
};
class B2    //基类B2,构造函数有参数
{public:
    B2(int j) {cout<<"constructing B2 "<<j<<endl;}
};
class B3    //基类B3,构造函数无参数
{public:
    B3(){cout<<"constructing B3 *"<<endl;}
};
class C: public B2, public B1, public B3 
{
public:    //派生类的公有成员
    C(int a, int b, int c, int d): 
       B1(a),memberB2(d),memberB1(c),B2(b)  
    {
      cout<<"constructing c *"<<endl; 
    }
private: //派生类的私有对象成员 B1 memberB1; B2 memberB2; B3 memberB3; }; int main() { C obj(1,2,3,4); }

结果:

constructing B2 2
constructing B1 1
constructing B3 *
constructing B1 3
constructing B2 4
constructing B3 *
constructing c *

 

转载于:https://www.cnblogs.com/defen/p/5344896.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值