#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
C++ 虚函数 3--虚函数应用编程 动态联编/运行时联编
最新推荐文章于 2022-04-10 13:31:25 发布