要求编程实现一个继承体系,定义一个抽象基类Vehicle,含私有数据成员车速speed,车轮数量wheel。从Vehicle派生出自行车类Bicycle、汽车类Car;从Bicycle和Car中派生出摩托车类Motocycle。 (1)请定义以上类并定义相应构造函数完成数据成员初始化;(10分) (2)给以上各类都定义一个Display成员函数,输出数据成员speed和wheel,输出格式如下: cout<<";类名:";<<speed<";,";<<wheel<<endl; 具体实现时“类名”替换成对应的类名。(15分)
时间: 2023-06-10 11:07:08 浏览: 99
vehicle类_抽象类Vehicle_vehicle类_
5星 · 资源好评率100%
以下是实现代码:
```cpp
#include <iostream>
using namespace std;
// 抽象基类 Vehicle
class Vehicle {
protected:
int speed; // 车速
int wheel; // 车轮数量
public:
Vehicle(int s, int w) : speed(s), wheel(w) {}
virtual void Display() = 0; // 纯虚函数
};
// Bicycle 类,从 Vehicle 派生而来
class Bicycle : public Vehicle {
public:
Bicycle(int s, int w) : Vehicle(s, w) {}
void Display() {
cout << "类名:Bicycle;" << speed << "," << wheel << endl;
}
};
// Car 类,从 Vehicle 派生而来
class Car : public Vehicle {
public:
Car(int s, int w) : Vehicle(s, w) {}
void Display() {
cout << "类名:Car;" << speed << "," << wheel << endl;
}
};
// Motocycle 类,从 Bicycle 和 Car 派生而来
class Motocycle : public Bicycle, public Car {
public:
Motocycle(int s, int w) : Bicycle(s, w), Car(s, w) {}
void Display() {
cout << "类名:Motocycle;" << speed << "," << wheel << endl;
}
};
int main() {
// 创建对象并调用 Display 函数
Bicycle b(20, 2);
Car c(80, 4);
Motocycle m(120, 2);
b.Display();
c.Display();
m.Display();
return 0;
}
```
输出结果如下:
```
类名:Bicycle;20,2
类名:Car;80,4
类名:Motocycle;120,2
```
阅读全文