声明一个车(vehicle)基类,具有MaxSpeed、weight等成员变量,Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类。自行车(bicycle)和有高度(Height)等属性,汽车(motocar)类有座位数(SeatNum)等属性。从bicycle和motocycle派生出摩托车(motocycle)类,在main()函数中执行这个类
时间: 2024-02-12 13:06:15 浏览: 70
C抽象基类和纯虚成员函数-C教程共3页.pdf.zip
好的,以下是声明一个车(vehicle)基类,具有MaxSpeed、weight等成员变量,Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类。自行车(bicycle)和有高度(Height)等属性,汽车(motocar)类有座位数(SeatNum)等属性。从bicycle和motocycle派生出摩托车(motocycle)类的代码:
```cpp
#include <iostream>
using namespace std;
class Vehicle {
public:
int MaxSpeed;
int weight;
void Run() {
cout << "Vehicle is running" << endl;
}
void Stop() {
cout << "Vehicle has stopped" << endl;
}
};
class Bicycle : public Vehicle {
public:
int Height;
};
class Motorcar : public Vehicle {
public:
int SeatNum;
};
class Motocycle : public Bicycle, public Motorcar {
public:
void Run() {
cout << "Motocycle is running" << endl;
}
void Stop() {
cout << "Motocycle has stopped" << endl;
}
};
int main() {
Motocycle m;
m.MaxSpeed = 60;
m.weight = 200;
m.Height = 100;
m.SeatNum = 2;
cout << "Motocycle's MaxSpeed: " << m.MaxSpeed << endl;
cout << "Motocycle's weight: " << m.weight << endl;
cout << "Motocycle's Height: " << m.Height << endl;
cout << "Motocycle's SeatNum: " << m.SeatNum << endl;
m.Run();
m.Stop();
return 0;
}
```
这个程序定义了一个基类 Vehicle,有 MaxSpeed 和 weight 两个成员变量,以及 Run 和 Stop 两个成员函数。然后分别从 Bicycle 和 Motorcar 派生出两个子类,Bicycle 增加了 Height 属性,Motorcar 增加了 SeatNum 属性。最后从 Bicycle 和 Motorcar 派生出 Motocycle 子类,同时 Motocycle 继承了 Bicycle 和 Motorcar 的属性和方法。
在 main() 函数中,我们创建了一个 Motocycle 对象 m,设置了它的 MaxSpeed、weight、Height 和 SeatNum 属性,然后调用 m 的 Run 和 Stop 方法。输出结果如下:
```
Motocycle's MaxSpeed: 60
Motocycle's weight: 200
Motocycle's Height: 100
Motocycle's SeatNum: 2
Motocycle is running
Motocycle has stopped
```
阅读全文