在此基础上 列表项编译成功后,把vehicle设置成非虚基类,再编译一次
时间: 2023-12-04 08:03:03 浏览: 14
好的,以下是修改后的代码:
```cpp
#include <iostream>
using namespace std;
class vehicle {
public:
void run() {
cout << "vehicle is running" << endl;
}
};
class bicycle : public vehicle {
public:
void run() {
cout << "bicycle is running" << endl;
}
};
class motocar : 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` 中也不再使用虚继承。这意味着 `motocycle` 中会有两个 `vehicle` 实例。
输出结果如下:
```
vehicle is running
bicycle is running
motocar is running
motocar is running
motocycle is running
```
可以看到,由于没有使用虚继承,`motocycle` 中存在两个 `vehicle` 实例,因此调用 `motocycle` 的 `run()` 方法时,输出了两遍 `motocar is running`。