C++ 菱形继承:解决 'Vehicle' is an ambiguous base of 'Amphibious' 错误
这个错误是因为Vehicle类作为Amphibious类的多个基类之一,而在moving()函数中使用了Vehicle::getName(),编译器无法确定是使用哪个基类的成员函数。
为了解决这个问题,你可以在调用getName()函数时明确指定要使用的基类。例如,假设Vehicle是Amphibious的第一个基类,你可以使用Amphibious::Vehicle::getName()来调用Vehicle类的getName()函数。修改后的代码如下:
cout << 'A' << Car::getColor() << ' amphibious ship named ' << Amphibious::Vehicle::getName() << ' moving at ' << Boat::getDisplacement() << ' speed!' << endl;
另外,你也可以在Amphibious类中重新实现getName()函数,以在Amphibious类中返回合适的名称。这样就可以避免使用多个基类的成员函数,代码如下:
string getName() {
return 'Amphibious Vehicle';
}
然后在moving()函数中直接调用getName()函数,而无需指定基类,代码如下:
cout << 'A' << Car::getColor() << ' amphibious ship named ' << getName() << ' moving at ' << Boat::getDisplacement() << ' speed!' << endl;
请根据你的实际需求选择合适的解决方法。
原文地址: https://www.cveoy.top/t/topic/hOxQ 著作权归作者所有。请勿转载和采集!