美文网首页
C++学习第13课,多继承

C++学习第13课,多继承

作者: Mr小熊_1da7 | 来源:发表于2019-06-16 18:00 被阅读0次

    1 类的多继承

    class Sofabed : public Sofa,public Bed 

    两个都是公有继承,如果不写默认为私有继承。

    2 产生了二义性

    如上,Sofa 和Bed,如果都有weight变量。

    使用s.getWeight();/*error 二意性,引入虚拟继承*/

    可以使用

    s.Sofa::getWeight();

    s.Bed::getWeight();

    来区分,不过这样有点麻烦。

    3 虚拟继承

    1 先定义一个家具类


    class Furniture {

    private:

    int weight;

    public:

    void setWeight(int weight) { this->weight = weight;}

    int getWeight(void) {return this->weight;}

    }

    2 床和沙发都虚拟继承这个家具

    class Sofa : virtual public Furniture{

    private:

    int a;

    public:

    void watchTV(void) { cout<<"watch TV"<<endl;}

    };

    class Bed : virtual public Furniture{

    private:

    int b;

    public:

    void sleep(void) {cout<<"sleep"<<endl;}

    };

    3  沙发床多继承这沙发和床

    class Sofabed : public Sofa,public Bed {

    private:

    int c;

    };

    结论:虚继承时,共同的虚父类会存在于同个空间。

    相关文章

      网友评论

          本文标题:C++学习第13课,多继承

          本文链接:https://www.haomeiwen.com/subject/jjcefctx.html