c++实现设计一个名为Vehicle的抽象基类,这个基类包含:名称、颜色、门的数量、气缸数量、变速箱类型和油位表示。在添加一个名为horn的函数用来显示Vehicle喇叭发出的声音。print函数用来显示信息。horn函数和print函数都应该是虚函数。horn是个纯虚函数。类Taxi和Truck是派生类。 编写一个类的测试结构要求:将一个Taxi类型的对象和一个Truck类型的对象实例化,并创建一个基类指针数组分别指向这两个对象。 程序输出如下: Taxi: Number of doors:4 Number of cylinders:6 Transmission type:5 Color :yellow Fuel level:3.3 Truck: Number of doors:2 Number of cylinders:16 Transmission type:8 Color :black Fuel level:7.54 Taxi:beep beep! Truck:HOOOONK!
时间: 2024-03-23 22:40:45 浏览: 43
好的,下面是C++实现:
```c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Vehicle {
protected:
string name;
string color;
int num_doors;
int num_cylinders;
int transmission_type;
double fuel_level;
public:
Vehicle(string n, string c, int d, int cy, int t, double f) : name(n), color(c), num_doors(d), num_cylinders(cy), transmission_type(t), fuel_level(f){}
virtual void horn() = 0;
virtual void print_info() {
cout << name << ": Number of doors:" << num_doors << " Number of cylinders:" << num_cylinders << " Transmission type:" << transmission_type << " Color :" << color << " Fuel level:" << fuel_level << endl;
}
};
class Taxi : public Vehicle {
public:
Taxi(string n, string c, int d, int cy, int t, double f) : Vehicle(n, c, d, cy, t, f){}
void horn() override {
cout << "beep beep!" << endl;
}
};
class Truck : public Vehicle {
public:
Truck(string n, string c, int d, int cy, int t, double f) : Vehicle(n, c, d, cy, t, f){}
void horn() override {
cout << "HOOOONK!" << endl;
}
};
int main() {
Taxi taxi("Taxi", "yellow", 4, 6, 5, 3.3);
Truck truck("Truck", "black", 2, 16, 8, 7.54);
vector<Vehicle*> vehicles{&taxi, &truck};
for (auto vehicle : vehicles) {
vehicle->print_info();
vehicle->horn();
}
return 0;
}
```
程序输出如下:
```
Taxi: Number of doors:4 Number of cylinders:6 Transmission type:5 Color :yellow Fuel level:3.3
beep beep!
Truck: Number of doors:2 Number of cylinders:16 Transmission type:8 Color :black Fuel level:7.54
HOOOONK!
```
阅读全文