C++笔记:虚继承

  • Post author:
  • Post category:其他

虚继承解决的是菱形继承。

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;

}

 

 


版权声明:本文为xiaoyaolangwj原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。