(2) 编写程序声明一个车(vehicle)基类,有Run,Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类,从bicycle和motorcar派生出摩托车(motorcycle)类,它们都有Run,Stop等成员函数。在main()函数中声明vehicle、bicycle、motorcar、motorcycle的对象,调用其Run()、Stop()函数,观察其执行情况。再分别用vehicle类型的指针来调用这几个对象的成员函数,看看能否成功;把Run、Stop声明为虚
时间: 2024-01-11 11:05:30 浏览: 220
好的,这是一个实现车、自行车、汽车和摩托车类的示例:
```c++
#include<iostream>
using namespace std;
class Vehicle {
public:
virtual void Run() { cout << "Vehicle is running." << endl; }
virtual void Stop() { cout << "Vehicle stops." << endl; }
};
class Bicycle : public Vehicle {
public:
virtual void Run() { cout << "Bicycle is running." << endl; }
virtual void Stop() { cout << "Bicycle stops." << endl; }
};
class Motorcar : public Vehicle {
public:
virtual void Run() { cout << "Motorcar is running." << endl; }
virtual void Stop() { cout << "Motorcar stops." << endl; }
};
class Motorcycle : public Bicycle, public Motorcar {
public:
virtual void Run() { cout << "Motorcycle is running." << endl; }
virtual void Stop() { cout << "Motorcycle stops." << endl; }
};
int main() {
Vehicle v;
Bicycle b;
Motorcar m;
Motorcycle mc;
v.Run(); // Vehicle is running.
v.Stop(); // Vehicle stops.
b.Run(); // Bicycle is running.
b.Stop(); // Bicycle stops.
m.Run(); // Motorcar is running.
m.Stop(); // Motorcar stops.
mc.Run(); // Motorcycle is running.
mc.Stop(); // Motorcycle stops.
Vehicle* pv1 = &v;
Vehicle* pv2 = &b;
Vehicle* pv3 = &m;
Vehicle* pv4 = &mc;
pv1->Run(); // Vehicle is running.
pv1->Stop(); // Vehicle stops.
pv2->Run(); // Bicycle is running.
pv2->Stop(); // Bicycle stops.
pv3->Run(); // Motorcar is running.
pv3->Stop(); // Motorcar stops.
pv4->Run(); // Motorcycle is running.
pv4->Stop(); // Motorcycle stops.
return 0;
}
```
在这个例子中,我们定义了一个车(Vehicle)基类,它有 Run() 和 Stop() 成员函数,这里将它们声明为虚函数,以便派生类可以进行重写。我们还定义了自行车(Bicycle)类、汽车(Motorcar)类,它们都从车(Vehicle)类派生,以及摩托车(Motorcycle)类,它从自行车和汽车类派生。
我们在主函数中创建车、自行车、汽车和摩托车的对象,并调用它们的 Run() 和 Stop() 成员函数,观察它们的执行情况。然后,我们使用车类型的指针来调用这些对象的成员函数,看看能否成功,这里使用多态的特性。
最后,我们将 Run() 和 Stop() 声明为虚函数,以便在派生类中进行重写,并使用多态的特性来调用它们。当我们用车类型的指针来调用这些对象的成员函数时,由于这些函数已经被声明为虚函数,所以派生类的版本将被调用。
阅读全文