32 继承(三)

来源:互联网 发布:阿里云ecs无法连接ftp 编辑:程序博客网 时间:2024/06/05 10:43

多重继承

#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
原创粉丝点击