严重性 代码 说明 项目 文件 行 禁止显示状态 错误(活动) E0286 基类 "vehicle" 不明确 test4-1zhengxu D:\c++zuoye\test4-1zhengxu\test4-1zhengxu\test4-1zhengxu.cpp 67
时间: 2023-07-07 09:40:50 浏览: 161
基于Qt开发的C++程序。利用assimp读取gltf/fbx等文件,并显示
5星 · 资源好评率100%
这个错误是因为我们在定义一个vehicle类型的指针时,由于motorcycle类同时继承了bicycle类和motorcar类,因此vehicle类会在motorcycle类中出现两次,导致编译器不知道应该使用哪个vehicle类。解决方案是使用虚继承(virtual inheritance)。
修改代码如下:
```c++
#include <iostream>
using namespace std;
class vehicle {
public:
virtual void Run() {
cout << "vehicle is running." << endl;
}
virtual void Stop() {
cout << "vehicle is stopped." << endl;
}
};
class bicycle : virtual public vehicle {
public:
virtual void Run() {
cout << "bicycle is running." << endl;
}
virtual void Stop() {
cout << "bicycle is stopped." << endl;
}
};
class motorcar : virtual public vehicle {
public:
virtual void Run() {
cout << "motorcar is running." << endl;
}
virtual void Stop() {
cout << "motorcar is stopped." << endl;
}
};
class motorcycle : public bicycle, public motorcar {
public:
virtual void Run() {
cout << "motorcycle is running." << endl;
}
virtual void Stop() {
cout << "motorcycle is stopped." << endl;
}
};
int main() {
vehicle v;
bicycle b;
motorcar m;
motorcycle mc;
v.Run();
v.Stop();
b.Run();
b.Stop();
m.Run();
m.Stop();
mc.Run();
mc.Stop();
vehicle* p;
p = &v;
p->Run();
p->Stop();
p = &b;
p->Run();
p->Stop();
p = &m;
p->Run();
p->Stop();
p = &mc;
p->Run();
p->Stop();
return 0;
}
```
在上述代码中,我们在bicycle类和motorcar类的继承声明中分别添加了`virtual`关键字,将其声明为虚继承。这样在motorcycle类继承这两个类时,就只会继承一个vehicle类,解决了编译器无法确定使用哪个vehicle类的问题。
阅读全文