编写程序声明一个车(vehicle)基类,由此派生出自行车(bicycle)类、汽车(motocar),注意把vehicle基类派生为虚基类。再从bicycle和motocar派生出摩托车(motocycle)类,在main()函数中执行这个类 C++
时间: 2024-02-12 21:07:17 浏览: 91
好的,以下是代码实现:
```cpp
#include <iostream>
using namespace std;
class vehicle {
public:
virtual void run() {
cout << "vehicle is running" << endl;
}
};
class bicycle : virtual public vehicle {
public:
void run() {
cout << "bicycle is running" << endl;
}
};
class motocar : virtual public vehicle {
public:
void run() {
cout << "motocar is running" << endl;
}
};
class motocycle : public bicycle, public motocar {
public:
void run() {
cout << "motocycle is running" << endl;
}
};
int main() {
vehicle* v = new vehicle();
v->run();
bicycle* b = new bicycle();
b->run();
motocar* m = new motocar();
m->run();
motocycle* mc = new motocycle();
mc->run();
delete v;
delete b;
delete m;
delete mc;
return 0;
}
```
在这个程序中,我们先声明了一个基类 `vehicle`,并将其声明为虚基类。然后分别从 `bicycle` 和 `motocar` 派生出两个类,并且都继承于 `vehicle`。最后从 `bicycle` 和 `motocar` 派生出 `motocycle` 类,它同时继承了 `bicycle` 和 `motocar`,因此也继承了 `vehicle`。
在 `main()` 函数中,我们实例化了每个类并调用了它们的 `run()` 方法。由于 `vehicle` 被声明为虚基类,因此 `motocycle` 中的 `vehicle` 只会有一个实例。
输出结果如下:
```
vehicle is running
bicycle is running
motocar is running
motocycle is running
```
阅读全文