1. 声明一个车(vehicle)基类,具有 MaxSpeed、Weight 等保护成员变量,由此派生出自行车(bicycle)类、汽车(motorcar)类。自行车(bicycle)类有高度(Height)等保护成员变量,汽车(motorcar)类有座位数(SeatNum)等保护成员变量。从 bicycle 和 motorcar 派生出摩托车(motocycle)类,在motocycle中有成员函数Display,输出所有成员数据信息(MaxSpeed、Weight、Height、SeatNum)。 每
时间: 2023-12-29 19:04:46 浏览: 210
个类都应该有默认构造函数和带参数构造函数,并且应该使用初始化列表初始化成员变量。
以下是代码示例:
```cpp
#include <iostream>
using namespace std;
class Vehicle {
protected:
int MaxSpeed;
int Weight;
public:
Vehicle() : MaxSpeed(0), Weight(0) {}
Vehicle(int maxSpeed, int weight) : MaxSpeed(maxSpeed), Weight(weight) {}
};
class Bicycle : public Vehicle {
protected:
int Height;
public:
Bicycle() : Vehicle(), Height(0) {}
Bicycle(int maxSpeed, int weight, int height) : Vehicle(maxSpeed, weight), Height(height) {}
};
class Motorcar : public Vehicle {
protected:
int SeatNum;
public:
Motorcar() : Vehicle(), SeatNum(0) {}
Motorcar(int maxSpeed, int weight, int seatNum) : Vehicle(maxSpeed, weight), SeatNum(seatNum) {}
};
class Motocycle : public Bicycle, public Motorcar {
public:
Motocycle() : Bicycle(), Motorcar() {}
Motocycle(int maxSpeed, int weight, int height, int seatNum)
: Vehicle(maxSpeed, weight), Bicycle(maxSpeed, weight, height), Motorcar(maxSpeed, weight, seatNum) {}
void Display() {
cout << "MaxSpeed: " << MaxSpeed << endl;
cout << "Weight: " << Weight << endl;
cout << "Height: " << Height << endl;
cout << "SeatNum: " << SeatNum << endl;
}
};
int main() {
Motocycle m(120, 200, 100, 2);
m.Display();
return 0;
}
```
在上面的代码中,我们定义了一个基类 `Vehicle`,它有 `MaxSpeed` 和 `Weight` 两个保护成员变量,并定义了自行车 `Bicycle` 和汽车 `Motorcar` 两个派生类。
在 `Bicycle` 类中,我们添加了 `Height` 保护成员变量。
在 `Motorcar` 类中,我们添加了 `SeatNum` 保护成员变量。
然后我们从 `Bicycle` 和 `Motorcar` 派生出摩托车 `Motocycle` 类,并在其中定义了一个 `Display` 函数,用于输出所有成员数据信息。
在 `main` 函数中,我们创建了一个 `Motocycle` 对象,调用了它的 `Display` 函数。在输出的信息中,我们可以看到这个摩托车的所有成员变量的值。
阅读全文