定义一个车(vehicle)基类,具有MaxSpeed、Weight等成员变量,Run、Stop等成员函数,由此派生出自 行车(bicycle)类、汽车(motorcar)类。自行车(bicycle)类有高度(Height)等属性,汽车(motorcar)类有座位数(SeatNum)等属性。从bicycle和motorcar派生出摩托车(motorcycle)类。注意:请不要将vehicle设置为虚基类进行实验。 输入 输出 vehicle is running... vehicle is stopped... bicycle is running... bicycle is stopped... motorcar is running... motorcar is stopped... motorcycle is running... motorcycle is stopped... --------------------------------------- vehicle is running... vehicle is stopped... vehicle is running... vehicle is stopped... vehicle is running... vehicle is stopped...
时间: 2024-01-31 10:02:46 浏览: 89
好的,这里是一个简单的车辆类的定义示例:
```c++
#include <iostream>
class Vehicle {
protected:
int MaxSpeed;
int Weight;
public:
Vehicle(int s, int w) : MaxSpeed(s), Weight(w) {}
virtual ~Vehicle() {}
virtual void Run() {
std::cout << "vehicle is running..." << std::endl;
}
virtual void Stop() {
std::cout << "vehicle is stopped..." << std::endl;
}
};
class Bicycle : public Vehicle {
private:
int Height;
public:
Bicycle(int s, int w, int h) : Vehicle(s, w), Height(h) {}
virtual ~Bicycle() {}
virtual void Run() {
std::cout << "bicycle is running..." << std::endl;
}
virtual void Stop() {
std::cout << "bicycle is stopped..." << std::endl;
}
};
class Motorcar : public Vehicle {
private:
int SeatNum;
public:
Motorcar(int s, int w, int n) : Vehicle(s, w), SeatNum(n) {}
virtual ~Motorcar() {}
virtual void Run() {
std::cout << "motorcar is running..." << std::endl;
}
virtual void Stop() {
std::cout << "motorcar is stopped..." << std::endl;
}
};
class Motorcycle : public Bicycle, public Motorcar {
public:
Motorcycle(int s, int w, int h, int n) : Bicycle(s, w, h), Motorcar(s, w, n) {}
virtual ~Motorcycle() {}
virtual void Run() {
std::cout << "motorcycle is running..." << std::endl;
}
virtual void Stop() {
std::cout << "motorcycle is stopped..." << std::endl;
}
};
```
在这里,我们定义了一个车辆类 `Vehicle`,它有两个成员变量 `MaxSpeed` 和 `Weight`,以及 `Run()` 和 `Stop()` 成员函数,用于表示车辆的最大速度和重量,以及行驶和停止的操作。注意,我们没有将 `Vehicle` 声明为虚基类,而是使用了普通的继承。
接着,我们定义了两个派生类 `Bicycle` 和 `Motorcar`,它们分别表示自行车和汽车,新增了一些属性(如 `Height` 和 `SeatNum`),并重写了 `Run()` 和 `Stop()` 函数,以便输出相应的信息。
最后,我们定义了 `Motorcycle` 类,它从 `Bicycle` 和 `Motorcar` 派生而来,表示摩托车。由于 `Bicycle` 和 `Motorcar` 都继承自 `Vehicle`,因此 `Motorcycle` 实际上继承了两份 `Vehicle` 的成员,需要注意解决二义性问题。在这里,我们直接使用了 `Vehicle` 的成员,并重写了 `Run()` 和 `Stop()` 函数。
可以看到,通过这样的设计,我们可以很方便地创建各种类型的车辆,并进行相应的操作:
```c++
int main() {
Vehicle* pV = new Vehicle(0, 0);
pV->Run();
pV->Stop();
delete pV;
Bicycle* pB = new Bicycle(30, 10, 1);
pB->Run();
pB->Stop();
delete pB;
Motorcar* pM = new Motorcar(120, 1000, 5);
pM->Run();
pM->Stop();
delete pM;
Motorcycle* pMC = new Motorcycle(80, 200, 2, 1);
pMC->Run();
pMC->Stop();
delete pMC;
return 0;
}
```
输出结果为:
```
vehicle is running...
vehicle is stopped...
bicycle is running...
bicycle is stopped...
motorcar is running...
motorcar is stopped...
motorcycle is running...
motorcycle is stopped...
```
可以看到,不同的车辆类型都能够正确地输出相应的信息。
阅读全文