C++构造一个类的对象的一般顺序

#include <iostream>
using namespace std;
class Base0                    // 基类Base0的声明
{
     public:
          Base0(int y)     { x=y; cout<<"x of Base0: "<<x<<endl;}
          int x;

};
class Base1 : virtual public Base0     // Base0为虚基类,公有派生Base1类
{
     public:
          Base1(int y):Base0(y)    { cout<<"x of Base1: "<<x<<endl;}
};

class Base2 : virtual public Base0     // Base0为虚基类,公有派生Base2类
{
     public:
          Base2(int y):Base0(y)    { cout<<"x of Base2: "<<x<<endl;}
};

class Child : public Base1, public Base2
{
     public:
          Child(int y,int u,int v,int w,int m,int n):Base0(y),Base1(y),Base2(y),B2(w),B0(u),B1(v),m(m),n(n){ cout<<"x m n of Child: "<<x<<" "<<m<<" "<<n<<endl;}
          Base0 B0;
          Base1 B1;
          Base2 B2;
          int m;
          int n;
};
int main()
{
      Child child(1,2,3,4,5,6);

      return 0;
}

在这里插入图片描述
由结果可知构造对象child 的顺序为:
1.执行虚基类的构造函数
2.按继承列表次序执行非虚基类构造函数(不再执行虚基类的构造函数)
3.按定义顺序进行派生类新增成员对象初始化(若新增对象未出现在初始化列表中,执行默认构造函数)
4.基本数据类型初始化
5.执行函数体

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值