32 继承(三)

多重继承

#include <iostream>
using namespace std;

class Furniture
{
public:
    Furniture(int weight) : weight_(weight)
    {
        cout << "Furniture ..." << endl;
    }
    ~Furniture()
    {
        cout << "~Furniture ..." << endl;
    }
    int weight_;

};
class Bed :virtual public Furniture
{
public:
    Bed(int weight) : Furniture(weight)
    {
        cout << "Bed ..." << endl;
    }
    ~Bed()
    {
        cout << "~Bed ..." << endl;
    }
    void Sleep()
    {
        cout << "Sleep ..." << endl;
    }
    int weight_;
};
class Sofa: virtual public Furniture
{
public:
    Sofa(int weight) : Furniture(weight)
    {
        cout << "Sofa ..." << endl;
    }
    ~Sofa()
    {
        cout << "~Sofa ..." << endl;
    }
    void WatchTV()
    {
        cout << "Watch TV ..." << endl;
    }
    int weight_;
};
class SofaBed : public Bed, public Sofa
{
public:
    SofaBed(int weight) :Bed(weight), Sofa(weight),Furniture(weight)
    {
        cout << "SofaBed ..." << endl;
        FoldIn();
    }
    ~SofaBed()
    {
        cout << "~SofaBed ..." << endl;
    }
    void FoldOut()
    {
        cout << "FoldOut ..." << endl;
    }
    void FoldIn()
    {
        cout << "FoldIn..." << endl;
    }

};
//在整个基础结构中,直接或间接继承虚基类的所有派生类,都必须在构造函数的成员初始化表中给出对
//虚基类的构造函数的调用。如果未列出,则表示调用该虚基类的默认构造函数

int main()
{
    SofaBed sofaBed(10);
    //sofaBed.weight_ = 20;//访问不明确,使用虚继承,可以解决二义性问题
    //sofaBed.weight_ = 10;

    sofaBed.Bed::weight_ = 10;
    sofaBed.Sofa::weight_ = 20;

    sofaBed.WatchTV();
    sofaBed.FoldOut();
    sofaBed.Sleep();
    return 0;
}

输出
先调用虚基类构造函数Furniture
调用Bed与Sofa的构造函数要按继承顺序,此时如果Furniture不是虚类,则会先调用其构造函数。Furniture的构造函数已经被最底层派生类SofaBed构造
最后调用最底层的派生类构造函数SofaBed

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值