新建文件”lab7_3.cpp“,编写程序声明一个车(vehicle)基类,由此派生出自行车(bicycle)类、汽车(motocar),注意把vehicle基类派生为虚基类。再从bicycle和motocar派生出摩托车(motocycle)类,在main()函数中执行这
时间: 2024-02-28 11:55:44 浏览: 62
个类的构造函数并输出结果。
以下是示例代码:
```c++
#include <iostream>
using namespace std;
class vehicle {
protected:
int wheels; // 轮子数
public:
virtual void show() { // 展示车辆信息
cout << "Vehicle with " << wheels << " wheels." << endl;
}
};
class bicycle : virtual public vehicle {
public:
bicycle() { // 自行车只有两个轮子
wheels = 2;
}
};
class motocar : virtual public vehicle {
public:
motocar() { // 汽车有四个轮子
wheels = 4;
}
};
class motocycle : public bicycle, public motocar {
public:
motocycle() {
// 摩托车继承自自行车和汽车,所以轮子数为 2 和 4 的和
wheels = bicycle::wheels + motocar::wheels;
}
void show() { // 重写展示车辆信息的方法
cout << "Motocycle with " << wheels << " wheels." << endl;
}
};
int main() {
motocycle mc;
mc.show();
return 0;
}
```
输出结果为:
```
Motocycle with 6 wheels.
```
阅读全文