C++:虚拟继承,多态示例

#pragma once
class Animal
{
public:
	Animal();
	~Animal();
	void SetWeight(int nWeight);	//设置重量
	int GetWeight();				//获得重量
private:
	int m_nWeight;
		 
};

#include "stdafx.h"
#include "Animal.h"
#include <string>
#include <iostream>
using namespace std;
Animal::Animal()
{
	cout << "Animal 类的构造函数被调用!" << endl;
}


Animal::~Animal()
{
	cout << "Animal 类的析构函数被调用!" << endl;
}
void Animal::SetWeight(int nWeight)	//设置重量
{
	m_nWeight=nWeight;

}
int Animal::GetWeight()				//获得重量
{
	return m_nWeight;
}
#pragma once
#include "Animal.h"

#include <iostream>
using namespace std;
class Horse :	virtual public Animal		//继承自Animal类,Animal类是虚基类
{
public:
	Horse();
	~Horse();
	void run();		//奔跑
};

#include "stdafx.h"
#include "Horse.h"


Horse::Horse()
{
	cout << "Horse 类的构造函数被调用!" << endl;
}


Horse::~Horse()
{
	cout << "Horse 类的析构函数被调用!" << endl;
}
void Horse::run()		//奔跑
{
	cout << "I can run!" << endl;
}
#pragma once
#include "Animal.h"
#include <iostream>
using namespace std;
class Bird : virtual public Animal //继承自Animal类,Animal类是虚基类
{
public:
	Bird();
	~Bird();
	void fly();		//奔跑
};

#include "stdafx.h"
#include "Bird.h"


Bird::Bird()
{
	cout << "Bird 类的构造函数被调用!" << endl;
}


Bird::~Bird()
{
	cout << "Bird 类的析构函数被调用!" << endl;
}
void Bird::fly()		//奔跑
{
	cout << "I can fly!" << endl;
}
#pragma once
#include "Horse.h"
#include "Bird.h"
class Pegasus : public Horse, public Bird		//多重继承
{
public:
	Pegasus();
	~Pegasus();
};

#include "stdafx.h"
#include "Pegasus.h"


Pegasus::Pegasus()
{
	cout << "Pegasus 类的构造函数被调用!" << endl;
}


Pegasus::~Pegasus()
{
	cout << "Pegasus 类的析构函数被调用!" << endl;
}
// HorseExample.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include"Pegasus.h"

int _tmain(int argc, _TCHAR* argv[])
{
	Pegasus p;		//定义一个对象
	p.run();
	p.fly();
	p.SetWeight(5);		//设置重量
	cout << p.GetWeight() << endl;
	getchar();
	return 0;
}

运行结果:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值