C++ 虚函数 3--虚函数应用编程 动态联编/运行时联编

80 篇文章 0 订阅
#include <iostream>
#include <string>
using namespace std;
/*---------------------------------
       13-03 虚函数应用编程之 拳击游戏
---------------------------------*/
class poser
{
public:
	virtual void beat()const
	{cout<<"一般选手的力量为260磅"<<endl;}	
protected:
	int age;
};
class Ali:public poser
{
public:
	void beat()const
	{cout<<"阿里一拳的力量为420磅"<<endl;}
};
class Lewis:public poser
{
public:
	void beat()const
	{cout<<"路易斯一拳的力量为480磅"<<endl;}
};
class Tyson:public poser
{
public:
	void beat()const
	{cout<<"泰森一拳的力量为500磅"<<endl;}
};
class Holy:public poser
{
public:
	void beat()const
	{cout<<"霍利一拳的力量为500磅"<<endl;}
};
int main()
{
	poser *p[5]; //定义1个指向包含5个基类对象的指针数组
	poser *p1;
	int choice,i;
	for(i=0;i<5;i++)
	{
		cout<<"1阿里 2路易斯 3泰森 4霍利"<<endl;
		cin>>choice;
		switch(choice)
		{
		case 1: 
			{p1 =new Ali; break;}
		case 2: 
			{p1 =new Lewis; break;}
		case 3: 
			{p1 =new Tyson; break;}
		case 4: 
			{p1 =new Holy; break;}
		default:
			{p1 =new poser; break;}
		}
		p[i] =p1;      //指针P是在我们输入一个数时,才指向某个对象的,这叫做
		p[i]->beat();  //动态联编或者运行时联编,相反,假如在运行之前,就确定
		 //哪个指针指向哪个对象,而且运行时不能更改的叫做静态联编或者编译时联编
		 //静态联编由于对象不用对自身进行跟踪,因此,速度浪费小
	}

	return 0;
}



运行结果:

1阿里 2路易斯 3泰森 4霍利
1
阿里一拳的力量为420磅
1阿里 2路易斯 3泰森 4霍利
2
路易斯一拳的力量为480磅
1阿里 2路易斯 3泰森 4霍利
3
泰森一拳的力量为500磅
1阿里 2路易斯 3泰森 4霍利
4
霍利一拳的力量为500磅
1阿里 2路易斯 3泰森 4霍利
5
一般选手的力量为260磅
Press any key to continue

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值