两个小程序看C++继承和组合的构造顺序

多继承

按照继承声明列表的顺序(笔者YY,即冒号后面的声明顺序)进行构造。
对象成员
按照在类中声明的顺序进行构造

#include <iostream>
#include <string>

using std::string;
using std::cout;
using std::endl;

class Base{
public :
    Base(int a, string s = "Default in Base"){
        cout << a << ":" << s << endl;
    }
};

class Base1 :virtual public Base{
public:
    Base1(int i, string s = "default in Base1", int j = 0) :Base(j, "Base of Base1"){
        cout << i << ":" << s << endl;
    }
};

class Base2 : public virtual Base{
public:
    Base2(int i, string s = "default in Base2", int j = 0) : Base(j, "Base of Base2"){
        cout << i << ":" << s << endl;
    }
};

class Son : public Base2, public Base1{
public:
    Son(int a, int b, int c, int d)
        :Base1(a, "Base1 from Son"), Base2(b, "Base2 From Son"), b1(c, "Object of Base1"),
        b2(d, "Object of Base2"), Base(a, "Base from Son"){
    }

private:
    Base2 b2;
    Base1 b1;
};

int main()
{
    Son s(1, 2, 3, 4);
    return 0;
}

结果如下:
这里写图片描述

继承与组合
对于拥有对象成员的类来说,构造顺序是:先构造对象成员,再构造自己,构造对象成员的顺序按照类中声明的顺序,示例如下:

#include <iostream>
#include <string>

using namespace std;

class A{
public:
    A()
    {
        cout << "A's ctor" << endl;
    }
};

class B
{
public:
    B()
    {
        cout << "B's ctor" << endl;
    }
};

class C{
public:
    C()
    {
        cout << "C's ctor" << endl;
    }

    B b;
    A a;
};

int main(int argc, char** argv)
{
    C c;
    return 0;
}

运行后的结果如下:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值