编写程序声明一个车(vehicle)基类,有run, stop等成员函数,由此派生出自行车(bicycle)类,汽车(motorcar)类,由bicycle和motorcar派生出摩托车(motorcycle)类。
时间: 2024-02-05 16:13:19 浏览: 27
以下是代码实现:
```c++
#include <iostream>
using namespace std;
// 车(vehicle)基类
class Vehicle {
public:
void run() {
cout << "Vehicle is running." << endl;
}
void stop() {
cout << "Vehicle has stopped." << endl;
}
};
// 自行车(bicycle)类,继承自车基类
class Bicycle : public Vehicle {
public:
void run() {
cout << "Bicycle is running." << endl;
}
void stop() {
cout << "Bicycle has stopped." << endl;
}
};
// 汽车(motorcar)类,继承自车基类
class Motorcar : public Vehicle {
public:
void run() {
cout << "Motorcar is running." << endl;
}
void stop() {
cout << "Motorcar has stopped." << endl;
}
};
// 摩托车(motorcycle)类,继承自自行车和汽车类
class Motorcycle : public Bicycle, public Motorcar {
public:
void run() {
cout << "Motorcycle is running." << endl;
}
void stop() {
cout << "Motorcycle has stopped." << endl;
}
};
int main() {
Vehicle v;
v.run();
v.stop();
Bicycle b;
b.run();
b.stop();
Motorcar m;
m.run();
m.stop();
Motorcycle mc;
mc.run();
mc.stop();
return 0;
}
```
输出结果如下:
```
Vehicle is running.
Vehicle has stopped.
Bicycle is running.
Bicycle has stopped.
Motorcar is running.
Motorcar has stopped.
Motorcycle is running.
Motorcycle has stopped.
```
从输出结果可以看出,派生类的成员函数可以覆盖基类的成员函数。同时,摩托车类继承了自行车和汽车类,因此可以调用它们的成员函数。