定义一个车(vehiele)基类,有Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类,从bicycle和motorcar派生出摩托车(motorcycle)类,它们都有Run、Stop等成员函数。观察虚函数的作用。
时间: 2024-03-23 20:36:28 浏览: 23
下面是一个定义车(vehiele)基类,有Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类,从bicycle和motorcar派生出摩托车(motorcycle)类的示例代码:
```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;
}
// 析构函数必须为虚函数,否则会导致内存泄漏
virtual ~Vehicle() {}
};
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* pVehicle1 = new Bicycle;
pVehicle1->Run();
pVehicle1->Stop();
delete pVehicle1;
Vehicle* pVehicle2 = new Motorcar;
pVehicle2->Run();
pVehicle2->Stop();
delete pVehicle2;
Vehicle* pVehicle3 = new Motorcycle;
pVehicle3->Run();
pVehicle3->Stop();
delete pVehicle3;
return 0;
}
```
在这个例子中,`Vehicle` 类是一个虚基类,它有两个虚函数 `Run()` 和 `Stop()`,并且析构函数也必须为虚函数,以防止内存泄漏。
`Bicycle` 类和 `Motorcar` 类都是从 `Vehicle` 类继承而来的,并且它们都重写了 `Run()` 和 `Stop()` 函数。`Motorcycle` 类是从 `Bicycle` 类和 `Motorcar` 类继承而来的,并且它也重写了 `Run()` 和 `Stop()` 函数。
在 `main()` 函数中,我们创建了三个指向 `Vehicle` 类的指针,分别指向 `Bicycle` 类、`Motorcar` 类和 `Motorcycle` 类的对象。然后,我们分别调用了它们的 `Run()` 和 `Stop()` 函数,观察到虚函数的作用。这里需要注意的是,为了防止内存泄漏,我们需要在使用完毕后删除指向这些对象的指针。