编写一个程序,有一个汽车类vehicle,它具有带参数的构造函数,显示输出函数,获得车轮个数、车重函数,类中的私有数据成员为车轮个数wheels和车重weight:;小车类car是汽车类vehicle公有派生类,其中包含载客人数 passenger load,获得载客人数、打印输出所有小车信息函数;卡车类truck是汽车类vehicle公有派生类,其中包含载客人数passenger load和载重量payload,获得载客人数,计算卡车效率函数efficiency0(效率:(载重量/(载重量+车重)),打印输出卡车所有信息函数,主函数创建小车类及卡车类对象,分别调用两个对象的显示输出函数。 第 hdows 以
时间: 2024-02-23 17:02:11 浏览: 101
好的,以下是代码实现:
```c++
#include <iostream>
using namespace std;
class Vehicle {
protected:
int wheels;
float weight;
public:
Vehicle(int w, float we) : wheels(w), weight(we) {}
void print() {
cout << "Wheels: " << wheels << endl;
cout << "Weight: " << weight << endl;
}
int get_wheels() { return wheels; }
float get_weight() { return weight; }
};
class Car : public Vehicle {
private:
int passenger_load;
public:
Car(int w, float we, int p) : Vehicle(w, we), passenger_load(p) {}
void print() {
Vehicle::print();
cout << "Passenger Load: " << passenger_load << endl;
}
int get_passenger_load() { return passenger_load; }
};
class Truck : public Vehicle {
private:
int passenger_load;
float payload;
public:
Truck(int w, float we, int p, float pay) : Vehicle(w, we), passenger_load(p), payload(pay) {}
void print() {
Vehicle::print();
cout << "Passenger Load: " << passenger_load << endl;
cout << "Payload: " << payload << endl;
}
int get_passenger_load() { return passenger_load; }
float efficiency() { return payload / (payload + weight); }
};
int main() {
Car car(4, 1000.0, 5);
car.print();
Truck truck(6, 5000.0, 2, 10000.0);
truck.print();
cout << "Truck Efficiency: " << truck.efficiency() << endl;
return 0;
}
```
主函数中我们创建了一个小车类对象和卡车类对象,然后调用了它们各自的 `print()` 函数,输出了它们的信息。此外,我们还调用了卡车类对象的 `efficiency()` 函数,计算并输出了它的效率。
阅读全文