虚继承解决的是菱形继承。
Animal下派生出Sheep和Tuo类。动物基类下,有两个派生类,一个是羊类,一个是驼类。这两个类都继承了Animal的一个属性,比如m_age。
这样就导致资源的浪费,同时sheepTuo二义性。
#include <iostream>
using namespace std;
class Animal
{
public :
int m_Age;
};
class Sheep:public Animal
{
};
class Tuo:public Animal
{};
class SheepTuo :public Sheep, public Tuo
{
};
void test01()
{
Sheep s;
s.m_Age = 10;
Tuo t;
t.m_Age = 20;
cout << s.m_Age << " " << t.m_Age << endl;
SheepTuo st;
st.Sheep::m_Age = 100;
st.Tuo::m_Age = 1000;
cout << st.Sheep::m_Age << " " << st.Tuo::m_Age << endl;
//cout << st.m_Age << endl;// 二义性无法访问。
}
int main()
{
test01();
return EXIT_SUCCESS;
}
通过VS开发者工具中的工具,我们可以查看类的结构。
cd切换到test.cpp所在的路径下,然后输入:
cl /d1 reportSingleClassLayoutSheepTuo test.cpp
解决方案:虚继承virtual。
#include <iostream>
using namespace std;
class Animal
{
public :
int m_Age;
};
class Sheep:virtual public Animal
{
};
class Tuo:virtual public Animal
{};
class SheepTuo :public Sheep, public Tuo
{
};
void test01()
{
Sheep s;
s.m_Age = 10;
Tuo t;
t.m_Age = 20;
cout << s.m_Age << " " << t.m_Age << endl;
SheepTuo st;
st.Sheep::m_Age = 100;
st.Tuo::m_Age = 1000;
cout << st.Sheep::m_Age << " " << st.Tuo::m_Age << endl;
cout << st.m_Age << endl;// 二义性无法访问。
}
int main()
{
test01();
return EXIT_SUCCESS;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)