现在的位置: 首页 > 综合 > 正文

C++ 虚继承 多重继承

2014年01月26日 ⁄ 综合 ⁄ 共 1176字 ⁄ 字号 评论关闭

一、整体代码

     01.cpp

#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)//不再调用Furniture(weight)
    {
        cout<<"Bed ..."<<endl;
    }
    ~Bed()
    {
        cout<<"~Bed ..."<<endl;
    }
    void Sleep()
    {
        cout<<"Sleep ..."<<endl;
    }
};
class Sofa : virtual public Furniture
{
public:
    Sofa(int weight) : Furniture(weight)//不再调用Furniture(weight)
    {
        cout<<"Sofa ..."<<endl;
    }
    ~Sofa()
    {
        cout<<"~Sofa ..."<<endl;
    }
    void WatchTV()
    {
        cout<<"Watch TV ..."<<endl;
    }
};
class SofaBed : public Bed, public Sofa
{
public:
    SofaBed(int weight) : Bed(weight), Sofa(weight), Furniture(weight)
           //首先是Furniture(weight),然后是Bed(weight), 
           //Sofa(weight),weight_不再有歧义了,只是 
           //Furniture(weight)生成了一次
    {
        cout<<"SofaBed ..."<<endl;
        FoldIn();
    }
    ~SofaBed()
    {
        cout<<"~SofaBed ..."<<endl;
    }
    void FoldOut()
    {
        cout<<"FoldOut ..."<<endl;
    }
    void FoldIn()
    {
        cout<<"FoldIn ..."<<endl;
    }
};
int main(void)
{
    SofaBed sofaBed(5);
    sofaBed.weight_ = 10;
    sofaBed.WatchTV();
    sofaBed.FoldOut();
    sofaBed.Sleep();
    return 0;
}

二、结果如下:

    Furniture ...
    Bed ...
    Sofa ...
    SofaBed ...


    FoldIn ...
    Watch TV ...
    FoldOut ...
    Sleep ... 


   ~SofaBed ...
   ~Sofa ...
   ~Bed ...
   ~Furniture ...

抱歉!评论已关闭.