如何添加“最终覆盖”来解决此问题?
#include <iostream>
struct Shape
{
virtual void print()
{
std::cout << "SHAPE" << std::endl;
}
virtual ~Shape() {}
};
struct Box : public virtual Shape
{
void print()
{
std::cout << "BOX" << std::endl;
}
};
struct Sphere : public virtual Shape
{
void print() final override
{
std::cout << "SPHERE" << std::endl;
}
};
struct GeoDisc : public Box, public Sphere
{
};
int main(int argc, char** argv)
{
Shape* s = new GeoDisc;
s->print();
delete s;
return 0;
}
这是错误信息:
31:8:错误:'GeoDisc'中'virtual void Shape :: print()'没有独特的最终覆盖
答案 0 :(得分:0)
虚拟方法声明中的关键字final
可以防止多重继承,因此如果我尝试在这种情况下解决歧义,那么这是一种错误的方法。如果Box和Sphere都有最后的单词,那么你将得到错误&#34;虚函数&#39; Shape :: print&#39;在GeoDisc&#39;中有超过一个最终覆盖者。法律模糊解决方案将是:
struct Sphere : public virtual Shape
{
void print() override
{
std::cout << "SPHERE" << std::endl;
}
};
struct GeoDisc : public Box, public Sphere
{
void print() final override
{
Sphere::print();
}
};