c++,要求编程实现一个继承体系,定义一个抽象基类Vehicle,含私有数据成员车速speed,车轮数量wheel。从Vehicle派生出自行车类Bicycle、汽车类Car;从Bicycle和Car中派生出摩托车类Motocycle。 (1)请定义以上类并定义相应构造函数完成数据成员初始化;(10分) (2)给以上各类都定义一个Display成员函数,输出数据成员speed和wheel,输出格式如下: cout<<";类名:";<<speed<";,";<<wheel<<endl; 具体实现时“类名”替换成对应的类名
时间: 2023-06-10 10:07:14 浏览: 51
以下是题目要求的代码实现:
```c++
#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
class Bicycle : public Vehicle {
public:
Bicycle(int s, int w) : Vehicle(s, w) {}
void Display() {
cout << "类名:Bicycle" << ";车速:" << speed << ",车轮数:" << wheel << endl;
}
};
// 汽车类 Car
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() {
Vehicle* vehicle[3]; // 创建一个指针数组,用于存储不同类型的车辆对象
vehicle[0] = new Bicycle(20, 2); // 创建自行车对象
vehicle[1] = new Car(80, 4); // 创建汽车对象
vehicle[2] = new Motocycle(120, 2); // 创建摩托车对象
// 调用 Display 函数,输出各个对象的信息
for (int i = 0; i < 3; i++) {
vehicle[i]->Display();
}
// 释放内存
for (int i = 0; i < 3; i++) {
delete vehicle[i];
}
return 0;
}
```
输出结果为:
```
类名:Bicycle;车速:20,车轮数:2
类名:Car;车速:80,车轮数:4
类名:Motocycle;车速:120,车轮数:2
```
注意,题目中要求对 Vehicle 类进行抽象,因此在 Vehicle 类中定义了一个纯虚函数 Display,这个函数没有具体的实现,也就是说 Vehicle 类是不能被实例化的,只能被用作基类。其他类都继承自 Vehicle 类,并实现了 Display 函数的具体输出内容。在 main 函数中创建了一个指针数组,用于存储不同类型的车辆对象,并通过循环调用 Display 函数输出各个对象的信息。最后注意要释放内存,否则会造成内存泄漏。