定义一个车(vehicle)基类,有虚函数Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类,它们都有Run、Stop等成员函数。在主函数中用不同的方法调用Run、Stop成员函数。
时间: 2024-02-26 15:59:30 浏览: 45
好的,以下是实现代码:
```c++
#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;
}
};
int main() {
Vehicle* v1 = new Bicycle();
v1->Run();
v1->Stop();
Vehicle* v2 = new Motorcar();
v2->Run();
v2->Stop();
delete v1;
delete v2;
return 0;
}
```
在这个示例中,我们定义了一个 `Vehicle` 类,它有两个虚函数 `Run` 和 `Stop`。然后我们派生了 `Bicycle` 类和 `Motorcar` 类,并重写了 `Run` 和 `Stop` 函数。
在 `main` 函数中,我们创建了 `Bicycle` 和 `Motorcar` 的对象,并将它们赋值给 `Vehicle` 类型的指针。然后我们通过这些指针调用 `Run` 和 `Stop` 函数。因为这些函数都是虚函数,所以会根据对象的实际类型来调用相应的函数。
最后,我们在程序结束前释放了动态分配的内存。