目录
使用虚继承解决菱形问题
菱形继承框图
我们会遇到一个问题:
派生类的子类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的析构函数,这说明我们声明的虚继承起作用了!
}