构建一个车(vehicle)基类,包含Run、Stop两个纯虚函数。由此基类,派生出(Car)轿车类,(truck)卡车类,在这两个类中别分定义Run和Stop两个函数,每个函数中输出 car 或者 truck is running 或 stopping。主函数中,分别实例化轿车类与卡车类,并构建基类指针,分别调用两个派生类对象的Run和Stop函数。
时间: 2024-03-10 20:44:24 浏览: 13
好的,我可以帮你解决这个问题。以下是实现该问题的 C++ 代码:
```cpp
#include <iostream>
using namespace std;
//定义车(Vehicle)基类
class Vehicle {
public:
//纯虚函数 Run
virtual void Run() = 0;
//纯虚函数 Stop
virtual void Stop() = 0;
};
//定义轿车(Car)类
class Car : public Vehicle {
public:
//实现 Run 函数
void Run() {
cout << "car is running." << endl;
}
//实现 Stop 函数
void Stop() {
cout << "car is stopping." << endl;
}
};
//定义卡车(Truck)类
class Truck : public Vehicle {
public:
//实现 Run 函数
void Run() {
cout << "truck is running." << endl;
}
//实现 Stop 函数
void Stop() {
cout << "truck is stopping." << endl;
}
};
int main() {
//实例化轿车类对象
Car car;
//实例化卡车类对象
Truck truck;
//定义基类指针
Vehicle *pVehicle = NULL;
//调用轿车类对象的 Run 函数
pVehicle = &car;
pVehicle->Run();
//调用轿车类对象的 Stop 函数
pVehicle->Stop();
//调用卡车类对象的 Run 函数
pVehicle = &truck;
pVehicle->Run();
//调用卡车类对象的 Stop 函数
pVehicle->Stop();
return 0;
}
```
运行以上代码,输出结果为:
```
car is running.
car is stopping.
truck is running.
truck is stopping.
```
以上就是一个简单的 C++ 例子,演示了如何通过基类和派生类实现多态。希望能帮到你!