多继承与虚函数

#include <iostream>

using namespace std;

enum COLOR { Red, Green, Blue, White};

class Animal
{
public:
	Animal(int);
	virtual ~Animal() { cout << "Animal 析构函数被调用...\n"; }
	virtual int GetAge() { return itsAge;}
	virtual void SetAge(int age) { itsAge = age; }
private:
	int itsAge;
};

Animal::Animal(int age) : itsAge(age)
{
	cout << "Animal的构造函数被调用...\n";
}

class Horse : virtual public Animal   // 这个是虚继承,
{
public:
	Horse(COLOR color, int height, int age);
	virtual ~Horse(){ cout << "Horse的析构函数被调用...\n"; }
	virtual void Whinny() const { cout << "Whinny!.."; }
	virtual int GetHeight() const { return itsHeight;}
	virtual COLOR GetColor() const { return itsColor; }
private:
	int itsHeight;
	COLOR itsColor;
};

Horse::Horse(COLOR color,int height, int age) : itsColor(color), itsHeight(height), Animal(age)
{
	cout << "Horse构造函数被调用...\n";
}

class Bird : virtual public Animal  // 这个是虚继承,
{
public:
	Bird(COLOR color,bool migrates, int age);
	virtual ~Bird() { cout << "Bird 的析构函数被调用...\n"; }
	//           鸟叫
	virtual void Chirp() const { cout << "Chirp...\n"; }
	virtual void Fly() const { cout << "I can Fly!"; }
	virtual bool GetMigration() const { return itsMigration;}
	virtual COLOR GetColor() const { return itsColor;}
private:
	bool itsMigration;   // itsMigration 是代表的迁移,
	COLOR itsColor;
};

Bird::Bird(COLOR color, bool migrates, int age) : itsColor(color), itsMigration(migrates), Animal(age) // 构造函数, 
{
	cout << "Bird的构造函数被调用...\n";
}
// 多继承,就是Pegasus继承Horse而Horse又继承Animal,Pegasus继承Bird而又继承Animal,  用虚继承解决这种二义性的问题,
class Pegasus : public Horse,public Bird  // 多继承,会显示二义性问题,从Horse里边继承的和从Bird里边继承的一样就是二义性问题,
{
public:
	void Chirp() const { Whinny(); }
	Pegasus(COLOR,int,bool,long,int);
	~Pegasus() { cout << "Pegasus的析构函数被调用了...\n"; }
	virtual long GetNumberBelievers() const
	{
		return itsNumberBelievers;
	}
private:
	long itsNumberBelievers;
};

Pegasus::Pegasus(COLOR aColor,int height,bool migrates,long numberBelieve, int age)
	: Horse(aColor,height,age),
	Bird(aColor,migrates,age),
	itsNumberBelievers(numberBelieve),
	Animal(age)   // 这个是重点,
{
	cout << "Pegasus构造函数被调用...\n";
}


int main()
{
	Pegasus *pPeg = new Pegasus(Red,5,true,80,1);
	pPeg->Chirp();
	cout << endl;
	pPeg->Fly();
	cout << endl;
	pPeg->Whinny();
	cout << endl;
	cout << "有" << pPeg->GetNumberBelievers() << "人相信有飞马," << endl;

	// pPeg->GetColor(); // 在这里就会出现问题,不知道调用的是那一个的颜色,是Horse或Bird的,
	
	COLOR color = pPeg->Horse::GetColor();
	cout << "飞马的颜色:" << color << endl; // 输出的是0,代表的是red  因为COLOR是一个枚举,
	pPeg->Bird::GetColor();



	pPeg->GetAge();

	delete pPeg;
	return 0;
}

你可能感兴趣的:(多继承与虚函数)