编写程序定义一个车(vehicle)基类,有Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类,从bicycle和motorcar派生出摩托车(motorcycle)类,它们都有Run、Stop等成员函数。在main()函数中定义vehicle、bicycle、motorcar、motorcycle的对象,调用其Run()、Stop()函数,观察其执行情况。再分别用vehicle类型的指针来调用这几个对象的成员函数,看看能否成功;把Run、Stop定义为虚函数,观察虚函数的作用。
时间: 2023-12-10 22:37:13 浏览: 57
以下是符合要求的程序:
```cpp
#include<iostream>
using namespace std;
class vehicle{
public:
virtual void Run(){cout<<"vehicle is running."<<endl;}
virtual void Stop(){cout<<"vehicle has stopped."<<endl;}
};
class bicycle :public vehicle{
public:
void Run(){cout<<"bicycle is running."<<endl;}
void Stop(){cout<<"bicycle has stopped."<<endl;}
};
class motorcar : public vehicle{
public:
void Run(){cout<<"motorcar is running."<<endl;}
void Stop(){cout<<"motorcar has stopped."<<endl;}
};
class motorcycle : public bicycle, public motorcar{
public:
void Run(){cout<<"motorcycle is running."<<endl;}
void Stop(){cout<<"motorcycle has stopped."<<endl;}
};
int main(){
vehicle v;
bicycle b;
motorcar m;
motorcycle mc;
v.Run(); v.Stop();
b.Run(); b.Stop();
m.Run(); m.Stop();
mc.Run(); mc.Stop();
vehicle* p = &v; p->Run(); p->Stop();
p = &b; p->Run(); p->Stop();
p = &m; p->Run(); p->Stop();
p = &mc; p->Run(); p->Stop();
return 0;
}
```
输出结果为:
```
vehicle is running.
vehicle has stopped.
bicycle is running.
bicycle has stopped.
motorcar is running.
motorcar has stopped.
motorcycle is running.
motorcycle has stopped.
vehicle is running.
vehicle has stopped.
bicycle is running.
bicycle has stopped.
motorcar is running.
motorcar has stopped.
motorcycle is running.
motorcycle has stopped.
```
可以看到,虚函数的作用在于实现了多态性,通过基类的指针来调用派生类的成员函数时,能够正确的调用到对应的函数。
相关推荐
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)