有一个汽车类vehicle,它具有一个需要传递参数的构造函数,类中的数据成员包括:车轮个数wheels和车重weight作为保护成员;小车类car是它的私有派生类,其中包含载人数passengers;卡车类truck是vehicle的私有派生类,其中包含载人数passensers和载重量payload;每个类中有相应的输出函数,输出函数名见主函数。执行并输出结果。主函数如下:intmain(){vehicleobj1(4,4);cout<<"vehicleinformation:"<<endl;obj1.display();carobj2(4,2,5);cout<<endl<<"carinformation:"<<endl;obj2.display();truckobj3(8,6,2,20);cout<<endl<<"truckinformation:"<<endl;obj3.display();return0;}
时间: 2023-10-30 11:16:39 浏览: 46
这是同样的问题,我已经回答过了,以下是代码实现:
```c++
#include <iostream>
using namespace std;
class Vehicle {
protected:
int wheels;
int weight;
public:
Vehicle(int w, int we): wheels(w), weight(we) {}
void display() {
cout << "Wheels: " << wheels << endl;
cout << "Weight: " << weight << endl;
}
};
class Car: private Vehicle {
private:
int passengers;
public:
Car(int w, int we, int p): Vehicle(w, we), passengers(p) {}
void display() {
cout << "Wheels: " << wheels << endl;
cout << "Weight: " << weight << endl;
cout << "Passengers: " << passengers << endl;
}
};
class Truck: private Vehicle {
private:
int passengers;
int payload;
public:
Truck(int w, int we, int p, int pay): Vehicle(w, we), passengers(p), payload(pay) {}
void display() {
cout << "Wheels: " << wheels << endl;
cout << "Weight: " << weight << endl;
cout << "Passengers: " << passengers << endl;
cout << "Payload: " << payload << endl;
}
};
int main() {
Vehicle obj1(4, 4);
cout << "Vehicle Information:" << endl;
obj1.display();
Car obj2(4, 2, 5);
cout << endl << "Car Information:" << endl;
obj2.display();
Truck obj3(8, 6, 2, 20);
cout << endl << "Truck Information:" << endl;
obj3.display();
return 0;
}
```
输出结果为:
```
Vehicle Information:
Wheels: 4
Weight: 4
Car Information:
Wheels: 4
Weight: 2
Passengers: 5
Truck Information:
Wheels: 8
Weight: 6
Passengers: 2
Payload: 20
```
阅读全文