使用虚继承解决菱形问题

目录

 

使用虚继承解决菱形问题

菱形继承框图

用虚继承解决菱形继承的问题

对应类成员的继承关系

虚继承代码示例


使用虚继承解决菱形问题

菱形继承框图

 

我们会遇到一个问题:

派生类的子类D中会通过公有继承含有两个基类A的成员,这两个基类A的成员分别来自于派生类B与派生类C,那加入类D中有个公有数据成员age,那我们给D类中的age成员变量赋值时,得做如下操作:

D::B::age=15;

D::C::age=15;

这太麻烦了,而且当你调用age时,也先声明清楚是从哪个父类继承的:

D::C::age

D::B::age

不但调用麻烦,还会出现各种各样的错误,占用浪费大量内存.

用虚继承解决菱形继承的问题

 

对应类成员的继承关系

 

虚继承代码示例

#include <iostream>  
#include <string>  
using namespace std;  
  
class Cperson  
{  
private:  
    float height;  
    float weight;  
public:  
    Cperson(float height, float weight)  
    {  
        this->height = height;  
        this->weight = weight;  
    }  
    ~Cperson()  
    {  
        cout << "调用Cperson的析构函数" << endl;  
    }  
};  
class Cdad :virtual public Cperson  
{  
private:  
    string name;  
    char sex;  
public:  
    Cdad(string name, char sex, float height, float weight) :Cperson(height, weight)  
    {  
        this->name = name;  
        this->sex = sex;  
    }  
    ~Cdad()  
    {  
        cout << "调用Cdad析构函数" << endl;  
    }  
    void ShowInf()  
    {  
        cout << "爸爸的名字是" << this->name << ";性别为" << this->sex << endl;  
    }  
};  
class Cmom :virtual public Cperson  
{  
private:  
    string name;  
    char sex;  
public:  
    Cmom(string name, char sex, float height, float weight) :Cperson(height, weight)  
    {  
        this->name = name;  
        this->sex = sex;  
    }  
    ~Cmom()  
    {  
        cout << "调用Cmom析构函数" << endl;  
    }  
    void ShowInf()  
    {  
        cout << "妈妈的名字是" << this->name << ";性别为" << this->sex << endl;  
    }  
};  
class CChildren :virtual public Cdad, virtual public Cmom  
{  
private:  
    string name;  
    char sex;  
public:  
    CChildren(string name, char sex, string Mname, char Msex, string Dname, char Dsex, float height, float weight) :  
        Cdad(Dname, Dsex, height, weight), Cmom(Mname, Msex, height, weight), Cperson(height, weight) // 把所有类全部初始化  
    {  
        this->name = name;  
        this->sex = sex;  
    }  
    ~CChildren()  
    {  
        cout << "调用CChildren析构函数" << endl;  
    }  
    void ShowInf()  
    {  
        Cdad::ShowInf();  
        Cmom::ShowInf();  
        cout << "孩子的名字是" << this->name << ";孩子的性别是" << this->sex << endl;  
    }  
};  
  
int main()  
{  
    CChildren children("son", 'm', "老妈", 'f', "老爸", 'm', 89.3, 45.2);  
    children.ShowInf();  
    // 我们看到只出现一个Cperson的析构函数,这说明我们声明的虚继承起作用了!  
}  

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肥肥胖胖是太阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值