Description
有一个交通工具类vehicle,将它作为基类派生小车类car、飞机类plane和轮船类ship。编程序显示每个交通工具的运行状态。
要求用一个函数通过传一个交通工具类定义的指针形式,实现在该函数内部实现状态输出(就是要求用虚函数)。
Input
第一个数是一个整数n,表示有n组数据。
每组数第1个数是1个整数:1——小车、2——飞机、3——轮船,第2个数是交通工具的运行速度。
Output
每个交通工具的运行速度,如Sample Output所示。
Sample Input
4
2 550
1 80
3 20
3 34
Sample Output
A plane is running in air at 550km/h.
A car is running on the road at 80km/h.
A ship is running in the sea at 20km/h.
A ship is running in the sea at 34km/h.
//交通工具
#include<bits/stdc++.h>
using namespace std;
class vehicle
{
public:
int speed;
virtual void run()
{
printf("A vehicle is running on the road at %dkm/h.\n",speed);
}
}v;
class car: public vehicle
{
public:
virtual void run()
{
printf("A car is running on the road at %dkm/h.\n",speed);
}
}c;
class plane: public vehicle
{
public:
virtual void run()
{
printf("A plane is running in air at %dkm/h.\n",speed);
}
}p;
class ship:public vehicle
{
public:
virtual void run()
{
printf("A ship is running in the sea at %dkm/h.\n",speed);
}
}s;
int main()
{
int n,i,a,b;
scanf("%d",&n);
vehicle *h;
/*car c;
plane p;
ship s;*/
for(i=0; i<n; i++)
{
scanf("%d%d",&a,&b);
if(a==1)
{
h=&c;
h->speed=b;
h->run();
}
else if(a==2)
{
h=&p;
h->speed=b;
h->run();
}
else if(a==3)
{
h=&s;
h->speed=b;
h->run();
}
}
}