5.编写程序声明一个Vehicle基类,有Run,Stop两个虚成员函数,由此类派生出Bicycle类,Motorcar类,从Bicycle和Motorcar派生出摩托车Motorcycle类,它们都覆盖改写了从基类继承过来的Run,Stop函数。在main函数中对上述内容进行多态测试。
时间: 2023-09-20 14:09:07 浏览: 89
以下是实现上述要求的程序:
```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* v1 = new Bicycle();
Vehicle* v2 = new Motorcar();
Vehicle* v3 = new Motorcycle();
v1->Run();
v1->Stop();
cout << endl;
v2->Run();
v2->Stop();
cout << endl;
v3->Run();
v3->Stop();
cout << endl;
delete v1;
delete v2;
delete v3;
return 0;
}
```
输出结果为:
```
Bicycle is running.
Bicycle has stopped.
Motorcar is running.
Motorcar has stopped.
Motorcycle is running.
Motorcycle has stopped.
```
在本程序中,`Vehicle` 类是一个基类,包含了 `Run()` 和 `Stop()` 两个虚成员函数。`Bicycle` 类和 `Motorcar` 类都继承了 `Vehicle` 类,并且覆盖了 `Run()` 和 `Stop()` 函数,实现了自己的行驶和停止方式。`Motorcycle` 类继承了 `Bicycle` 类和 `Motorcar` 类,因此可以调用 `Bicycle` 和 `Motorcar` 的函数,同时也可以覆盖它们的函数,实现自己的行驶和停止方式。
在 `main()` 函数中,分别创建了 `Bicycle`、`Motorcar` 和 `Motorcycle` 对象,并通过基类指针进行调用,实现了多态。
阅读全文