用C++编写一个程序,其中有一个汽车类Vehicle,它具有一个需要传递参数的构造函数,类中的数据成员:车轮个数wheels和车重weight为保护属性;小车类Car是它的私有派生类,其中包含载人数passager_load;卡车类Truck是Vehicle的私有派生类,其中包含载人数passager_load和载重量payload。每个类都有相关数据的输出方法。
时间: 2024-02-15 15:01:49 浏览: 29
好的,以下是符合您要求的 C++ 代码:
```c++
#include <iostream>
using namespace std;
class Vehicle {
protected:
int wheels;
double weight;
public:
Vehicle(int w, double wt) : wheels(w), weight(wt) {}
virtual void display() {
cout << "Wheels: " << wheels << endl;
cout << "Weight: " << weight << " kg" << endl;
}
};
class Car : private Vehicle {
private:
int passenger_load;
public:
Car(int w, double wt, int p) : Vehicle(w, wt), passenger_load(p) {}
void display() {
cout << "Car" << endl;
Vehicle::display();
cout << "Passenger load: " << passenger_load << endl;
}
};
class Truck : private Vehicle {
private:
int passenger_load;
double payload;
public:
Truck(int w, double wt, int p, double pay) : Vehicle(w, wt), passenger_load(p), payload(pay) {}
void display() {
cout << "Truck" << endl;
Vehicle::display();
cout << "Passenger load: " << passenger_load << endl;
cout << "Payload: " << payload << " kg" << endl;
}
};
int main() {
Vehicle* v1 = new Vehicle(4, 1000);
v1->display();
cout << endl;
Car* c1 = new Car(4, 1200, 5);
c1->display();
cout << endl;
Truck* t1 = new Truck(6, 5000, 3, 2000);
t1->display();
cout << endl;
delete v1;
delete c1;
delete t1;
return 0;
}
```
在这个程序中,我们首先定义了一个基类 `Vehicle`,有两个保护属性 `wheels` 和 `weight`,并且有一个需要传递参数的构造函数。然后我们定义了一个私有派生类 `Car` 和一个私有派生类 `Truck`,它们分别包含了各自的特有属性 `passenger_load` 和 `payload`,并且都有一个需要传递参数的构造函数。每个类都有一个 `display()` 方法用于输出相关数据。在 `main()` 函数中我们实例化了一个 `Vehicle` 对象、一个 `Car` 对象和一个 `Truck` 对象,并分别调用它们的 `display()` 方法输出相关数据。最后我们删除这些对象以释放内存。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)