用C++编写一个程序,有一个汽车类vehicle,它具有一个需要传递参数的构造函数,类中的数据成员:车轮个数wheels和车重weight放在保护段中;小车类car是它的私有派生类,其中包含载人数passenger_load;卡车类truck是vehicle的私有派生类,其中包含载人数passenger_load和载重量payload和一个求载率的函数efficiency()(假设用 payload/( payload + weight)计算)。每个类都有相关数据的输出方法,并设计主函数测试。
时间: 2023-06-07 15:09:51 浏览: 230
没问题,下面是符合要求的 C++ 代码:
```
#include<iostream>
using namespace std;
class Vehicle{
protected:
int wheels, weight;
public:
Vehicle(int w, int wei){
wheels = w;
weight = wei;
}
void show(){
cout << "Wheels: " << wheels << endl;
cout << "Weight: " << weight << endl;
}
};
class Car : private Vehicle{
private:
int passenger_load;
public:
Car(int w, int wei, int pl) : Vehicle(w,wei){
passenger_load = pl;
}
void show(){
Vehicle::show();
cout << "Passenger load: " << passenger_load << endl;
}
};
class Truck : private Vehicle{
private:
int passenger_load, payload;
public:
Truck(int w, int wei, int pl, int pay) : Vehicle(w, wei){
passenger_load = pl;
payload = pay;
}
float efficiency(){
return ((float)payload/(payload + weight));
}
void show(){
Vehicle::show();
cout << "Passenger load: " << passenger_load << endl;
cout << "Payload: " << payload << endl;
}
};
int main(){
Vehicle v(4, 1000);
Car c(4, 800, 5);
Truck t(8, 5000, 2, 1000);
v.show();
cout << "----------------------------\n";
c.show();
cout << "----------------------------\n";
t.show();
cout << "Efficiency: " << t.efficiency()<< endl;
return 0;
}
```
希望这段代码能够解决您的问题,如还有任何问题或疑问,欢迎随时向我提问哦。
阅读全文