多继承与虚基类

  • 多继承
  • 多继承中的二义性问题
  • 虚基类
  • 虚基类的构造函数
#include <iostream>

using namespace std;

enum COLOR { Red, Green, Blue, Yellow, White, Black, Brown };

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 : public virtual Animal
{
public:
	Horse(COLOR itsColor ,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) :Animal(age), itsHeight(height), itsColor(color)
{
	cout << "Horse构造函数被调用....\n" <<endl;
}

class Bird : public virtual Animal 
{
	public:
		Bird(COLOR color, bool migrates, int age);
		virtual ~Bird() { cout << "Bird析构函数被调用...\n" ;};
		virtual void Chirp() const { cout << "Chirp...."; }
		virtual void Fly() const {
			cout << "I can fly! I can fly! I can fly!";
		}
		virtual bool GetMigration() const { return itsMigration; }
		virtual COLOR GetColor() const { return itsColor; }
	private:
		bool itsMigration;
		COLOR itsColor;
};

Bird::Bird(COLOR color, bool migrates, int age) :Animal(age), itsMigration(migrates), itsColor(color)
{
	cout << "Bird构造函数被调用...\n";
}

class Pegasus : public Horse, public Bird
{
	public:
		void Chirp() const { Whinny(); }
		Pegasus(COLOR, int, bool, long, int);
		~Pegasus() { cout << "Pegasus析构函数被调用...\n"; }
		virtual long GetNumberBelievers() const
		{
			return itsNumberBelivers;
		}
	private:
		long itsNumberBelivers;
};

Pegasus::Pegasus(COLOR aColor, int height, bool migrates, long numBelieve, int age): Horse(aColor, height, age), Bird(aColor, migrates, age), itsNumberBelivers(numBelieve),Animal(age)
{
	cout << "Pegasus构造函数被调用...\n";	
};

int main()
{
	Pegasus *pPeg = new Pegasus(Blue, 5, true, 10, 2);	
	pPeg->Fly();
	pPeg->Whinny();
	pPeg->Chirp();
	cout << "有" << pPeg->GetNumberBelievers() << "人相信世界上有飞马" << endl;

	COLOR color = pPeg->Bird::GetColor();
	cout << "飞马的颜色:" << color << endl;

	pPeg->GetAge();

	delete pPeg;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值