实验九 多态性与虚函数(2)
一、实验目的和要求
1. 2. 3. 4.
了解多态的概念;
了解虚函数的作用及使用方法;
了解静态关联和动态关联的概念和用法; 了解纯虚函数和抽象类的概念和用法
二、实验内容和结果
1. 声明一个车(vehicle)基类,具有MaxSpeed、weight等成员变量有Run、Stop等成员
函数,由此派生出自行车(bicycle)类、汽车(motorcar)类,自行车(bicycle)类有高度(Height)等属性,汽车(motorcar)有座位数(SeatNum)等属性,类从bicycle和motorcar派生出摩托车(motorcycle)类,它们都有Run、Stop等成员函数,使用虚函数完成。(各个类都必须定义构造函数和析构函数)
#include
protected:
float MaxSpeed; float weight; public:
~vehicle(){}
vehicle(float m,float w):MaxSpeed(m),weight(w){} virtual void Run () {
cout<<\车已经启动啦!!!\< } virtual void Stop () { cout<<\已经停啦!!!\< class bicycle: virtual public vehicle { protected: float Height; public: ~bicycle(){} bicycle(float m,float w,float h):vehicle( m,w),Height(h){} void Run () { cout<<\is:\< void Stop () { cout<<\已经停啦!!!\< } }; class motorcar: virtual public vehicle { protected: int SeatNum; public: ~motorcar(){} motorcar(float m,float w,float s):vehicle( m,w),SeatNum(s){} void Run () { cout<<\is:\< void Stop () { cout<<\已经停啦!!!\< class motorcycle: public bicycle, public motorcar