构建一个车(vehicle)基类,包含Run、Stop两个纯虚函数。由此基类,派生出(Car)轿车类,(truck)卡车类,在这两个类中别分定义Run和Stop两个函数,每个函数中输出 car 或者 truck is running 或 stopping。主函数中,分别实例化轿车类与卡车类,并构建基类指针,分别调用两个派生类对象的Run和Stop函数。
时间: 2024-03-10 11:44:55 浏览: 29
纯虚函数-非常经典的C++教程
好的,下面是代码实现:
```c++
#include<iostream>
using namespace std;
class Vehicle {
public:
virtual void Run() = 0;
virtual void Stop() = 0;
};
class Car : public Vehicle {
public:
virtual void Run() {
cout << "Car is running." << endl;
}
virtual void Stop() {
cout << "Car is stopping." << endl;
}
};
class Truck : public Vehicle {
public:
virtual void Run() {
cout << "Truck is running." << endl;
}
virtual void Stop() {
cout << "Truck is stopping." << endl;
}
};
int main() {
Car car;
Truck truck;
Vehicle* p = &car;
p->Run();
p->Stop();
p = &truck;
p->Run();
p->Stop();
return 0;
}
```
输出结果为:
```
Car is running.
Car is stopping.
Truck is running.
Truck is stopping.
```
希望这个例子能帮助你理解如何使用 C++ 的纯虚函数和类的继承。
阅读全文