/*定义一个车(vehicle)基类,具有MaxSpeed、Weight等成员变量,Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类。
自行车(bicycle)类有高度(Height)等属性,汽车(motorcar)类有座位数(SeatNum)等属性。从bicycle和motorcar派生出摩托车(motorcycle)类。
请分别将vehicle设置为虚基类和不设置vehicle为虚基类进行实验*/
#include <iostream>
#include<cstring>
using namespace std;
class vehicle
{
protected:
int MaxSpeed;
int Weight;
public:
vehicle(int m1,int w1)
{
MaxSpeed=m1;
Weight=w1;
}
vehicle(){};
virtual void run()
{
cout<<"vehicle runs."<<endl;
}
virtual void show()
{
cout<<"vehicle MaxSpeed="<<MaxSpeed<<endl;
cout<<"vehicle Weight="<<Weight<<endl;
}
virtual void stop()
{
cout<<"vehicle stop."<<endl;
}
};
class bicycle:virtual public vehicle
{
protected:
int heigh;
public:
bicycle(int m2,int w2,int h1)
{
MaxSpeed=m2;
Weight=w2;
heigh=h1;
}
bicycle(){}
virtual void run()
{
cout<<"bicycle runs."<<endl;
}
virtual void show()
{
cout<<"bicycle MaxSpeed="<<MaxSpeed<<endl;
cout<<"bicycle Weight="<<Weight<<endl;
cout<<"bicycle height="<<heigh<<endl;
}
virtual void stop()
{
cout<<"bicycle stops."<<endl;
}
};
class motorcar:virtual public vehicle
{
protected:
int SetNum;
public:
motorcar(int m3,int w3,int s1)
{
MaxSpeed=m3;
Weight=w3;
SetNum=s1;
}
motorcar(){};
virtual void run()
{
cout<<"motorcar runs."<<endl;
}
virtual void show()
{
cout<<"motorcar MaxSpeed="<<MaxSpeed<<endl;
cout<<"motorcar Weight="<<Weight<<endl;
cout<<"motorcar SetNum="<<SetNum<<endl;
}
virtual void stop()
{
cout<<"motorcar stops."<<endl;
}
};
class motorcycle:public bicycle,public motorcar
{
public:
motorcycle(int m4,int w4,int h2,int s2)
{
MaxSpeed=m4;
Weight=w4;
heigh=h2;
SetNum=s2;
}
motorcycle(){};
virtual void run()
{
cout<<"motorcycle runs."<<endl;
}
virtual void show()
{
cout<<"motorcycle MaxSpeed="<<MaxSpeed<<endl;
cout<<"motorcycle Weight="<<Weight<<endl;
cout<<"motorcycle heigh="<<heigh<<endl;
cout<<"motorcycle SetNum="<<SetNum<<endl;
}
virtual void stop()
{
cout<<"motorcycle stops."<<endl;
}
};
int main()
{
vehicle v(108,20);
bicycle b(103,30,40);
motorcar m(180,43,53);
motorcycle n(145,63,45,56);
vehicle *a[4]={&v,&b,&m,&n};
for(int i=0;i<4;i++)
{
a[i]->run();
a[i]->show();
a[i]->stop();
}
}
main函数的实现为啥一定得用指针呢,为啥每一个函数都要写成虚函数,有别的实现代码吗?
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- [PE]经典八炮 2022-02-06 13:13关注
这是面向对象的重要特征之一——多态,在大型应用程序中应用很广,你想象一个游戏,有很多角色,它们不同类型,如果想更新所有的角色,怎么办?可以将所有的类型都派生自同一个类,提供一个Update虚函数,所有类都要重写这个函数,然后用基类指针数组存储所有的子类对象,更新所有角色的话,直接遍历数组,调用Update,根据多态定义,调用的是子类的Update,这样就实现了对所有角色的更新。你可以看看我的专栏C++游戏编程系列,里面的程序框架就用了多态原理。
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用
悬赏问题
- ¥30 STM32 INMP441无法读取数据
- ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
- ¥15 用visualstudio2022创建vue项目后无法启动
- ¥15 x趋于0时tanx-sinx极限可以拆开算吗
- ¥500 把面具戴到人脸上,请大家贡献智慧
- ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
- ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
- ¥30 c#打开word开启修订并实时显示批注
- ¥15 如何解决ldsc的这条报错/index error
- ¥15 VS2022+WDK驱动开发环境