天天看点

C++菱形继承中的多继承、多重继承、虚继承实例

C++菱形继承中的多继承、多重继承、虚继承实例

1.菱形继承:示意图如下

C++菱形继承中的多继承、多重继承、虚继承实例

B继承于A,C继承于A,D多重继承于B和C,则创建D类对象时,就会有基类A的两份拷贝。

2.多继承:即一个派生类可以有两个或多个基类。

3.多重继承:像上图B继承于A,D继承于B,这种继承关系便是多继承。

4.虚继承:虚基类用virtual声明。无论该类在派生层次中作为虚基类出现多少次,只继承一个共享的基类子对象,共享基类子对象称为虚基类。虚继承可用来解决菱形继承中的问题。

5.代码实例:

//多继承:ChildLabourer继承于Children和Worker
//多重继承:Person-Children- ChildLabourer和Person - Work - ChildLabourer
//虚继承:关键词virtual,由于初始化ChildLabourer时两次调用Person


#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;

/**
 * 定义人类: Person
 */
class Person
{
public:
	Person()
	{
		cout << "Person" << endl;
	}
	~Person()
	{
		cout << "~Person" << endl;
	}
	void eat()
	{
		cout << "eat" << endl;
	}

};

/**
 * 定义工人类: Worker
 * 虚继承人类
 */
class Worker : virtual public Person
{
public:
	Worker(string name)
	{
		m_strName = name;
		cout << "Worker" << endl;
	}
	~Worker()
	{
		cout << "~Worker" << endl;
	}
	void work()
	{
		cout << m_strName << endl;
		cout << "work" << endl;
	}
protected:
	string m_strName;
};

/**
 * 定义儿童类:Children
 * 虚继承人类
 */
class Children : virtual public Person
{
public:
	Children(int age)
	{
		m_iAge = age;
		cout << "Children" << endl;
	}
	~Children()
	{
		cout << "~Children" << endl;
	}
	void play()
	{
		cout << m_iAge << endl;
		cout << "play" << endl;
	}
protected:
	int m_iAge;
};

/**
 * 定义童工类:ChildLabourer
 * 公有继承工人类和儿童类
 */
class ChildLabourer :public Worker, public Children
{
public:
	ChildLabourer(string name, int age) :Worker(name), Children(age)
	{
		cout << "ChildLabourer" << endl;
	}

	~ChildLabourer()
	{
		cout << "~ChildLabourer" << endl;
	}
};

int main(void)
{
	// 用new关键字实例化童工类对象
	ChildLabourer *p = new ChildLabourer("jame", 8);
	// 调用童工类对象各方法。
	p->eat();
	p->work();
	p->play();
	delete p;
	p = NULL;

	system("pasue");
	return 0;
}
           

继续阅读