编写程序声明一个Vehicle基类,有Run,Stop两个虚成员函数,由此类派生出Bicycle类,Motorcar类,从Bicycle和Motorcar派生出摩托车Motorcycle类,它们都覆盖改写了从基类继承过来的Run,Stop函数。在main函数中对上述内容进行多态测试。
时间: 2023-09-08 12:08:46 浏览: 108
下面是一个简单的实现:
```cpp
#include <iostream>
using namespace std;
class Vehicle {
public:
virtual void Run() {
cout << "Vehicle is running." << endl;
}
virtual void Stop() {
cout << "Vehicle is stopped." << endl;
}
};
class Bicycle : public Vehicle {
public:
void Run() {
cout << "Bicycle is running." << endl;
}
void Stop() {
cout << "Bicycle is stopped." << endl;
}
};
class Motorcar : public Vehicle {
public:
void Run() {
cout << "Motorcar is running." << endl;
}
void Stop() {
cout << "Motorcar is stopped." << endl;
}
};
class Motorcycle : public Bicycle, public Motorcar {
public:
void Run() {
cout << "Motorcycle is running." << endl;
}
void Stop() {
cout << "Motorcycle is stopped." << endl;
}
};
int main() {
Vehicle* v1 = new Bicycle();
v1->Run(); //输出 Bicycle is running.
v1->Stop(); //输出 Bicycle is stopped.
Vehicle* v2 = new Motorcar();
v2->Run(); //输出 Motorcar is running.
v2->Stop(); //输出 Motorcar is stopped.
Vehicle* v3 = new Motorcycle();
v3->Run(); //输出 Motorcycle is running.
v3->Stop(); //输出 Motorcycle is stopped.
delete v1;
delete v2;
delete v3;
return 0;
}
```
在上述代码中,我们首先声明了一个`Vehicle`基类,其中包含了`Run()`和`Stop()`两个虚成员函数。然后我们从`Vehicle`派生出了`Bicycle`和`Motorcar`两个类,并且在这两个派生类中分别覆盖了`Run()`和`Stop()`函数。接着我们又从`Bicycle`和`Motorcar`这两个类派生出了`Motorcycle`类,并且在`Motorcycle`类中同样覆盖了`Run()`和`Stop()`函数。最后在`main()`函数中,我们对上述类进行多态测试。
我们分别声明了指向`Bicycle`、`Motorcar`和`Motorcycle`对象的指针,并且分别调用了它们的`Run()`和`Stop()`函数。由于这些函数都是虚函数,所以在运行时会根据对象的实际类型来调用相应的函数,从而实现了多态的效果。
阅读全文