已知由Automobille类派生出Car类和Wagon类,而后两者共同派生出StationWagon类。 (1)Automobile汽车类有数据成员马力:int power;有成员函数:Automobile(int p);和void Display(); (2)Car客车类有数据成员座位:int seat; 成员函数 Car(int p,int s);和void Display(); (3)Wagon货车类有数据成员装载量:int load; 成员函数:Wagon(int p,int l);和void Display(); (4)StationWagon 客货两用车类: StationWagon(int p, int s,int l);和void Display();成员函数。 输入描述 输入 马力、座位和承载量 样例输入 108 3 10 样例输出 StationWagon: Power:108 Seat:3 Load:10
时间: 2024-03-18 21:40:39 浏览: 21
好的,这是一个关于继承的问题,我可以帮您解答。
根据题目描述,我们可以得到以下类的继承关系:
```
Automobile
|
+---- Car
| |
| +---- StationWagon
|
+---- Wagon
|
+---- StationWagon
```
其中,`Automobile` 是基类,`Car` 和 `Wagon` 是直接派生类,`StationWagon` 是间接派生类,它同时继承了 `Car` 和 `Wagon`。
根据题目所给的类定义,我们需要在 `StationWagon` 类中再次定义一个构造函数和一个 `Display()` 函数,以便输出各个数据成员的值。
下面是一个可能的实现,您可以参考一下:
```cpp
class StationWagon : public Car, public Wagon {
public:
StationWagon(int p, int s, int l) : Automobile(p), Car(p, s), Wagon(p, l) {}
void Display() {
cout << "StationWagon: ";
cout << "Power:" << power << " ";
cout << "Seat:" << seat << " ";
cout << "Load:" << load << endl;
}
};
```
在上面的代码中,我们使用了多重继承(`public Car, public Wagon`)来继承 `Car` 和 `Wagon` 类中的所有数据成员和成员函数。然后,我们在 `StationWagon` 的构造函数中调用了基类的构造函数,以初始化 `power` 数据成员。最后,我们在 `Display()` 函数中输出各个数据成员的值。
接下来,我们可以在 `main()` 函数中创建一个 `StationWagon` 对象,并调用其 `Display()` 函数来输出结果:
```cpp
int main() {
int power, seat, load;
cin >> power >> seat >> load;
StationWagon sw(power, seat, load);
sw.Display();
return 0;
}
```
输入样例:
```
108 3 10
```
输出样例:
```
StationWagon: Power:108 Seat:3 Load:10
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)