我正在尝试使用虚拟类方法解决可怕的菱形继承(钻石问题)。
让我们首先考虑具有最终虚方法特性的多重继承情况。 由于存在 final方法,因此无法声明重写方法,但必须使用 using 声明来指定子类应使用哪个方法。
class Mother {
public:
virtual void foo() final {}
};
class Father {
public:
virtual void foo() {}
};
class Child: public Mother, public Father {
public:
// void foo() {Mother::foo();} // This clashes with Mother::foo being final
using Mother::foo;
};
上面的代码按预期工作。
但是,如果我们切换到具有抽象基类的类钻石结构,则相同的方法将不再起作用。
class GrandParent {
public:
virtual void foo() = 0;
};
class Mother: virtual public GrandParent{
public:
virtual void foo() override final {};
};
class Father: virtual public GrandParent{
public:
virtual void foo() override {};
};
class Child: public Mother, public Father {
using Mother::foo;
};
编译上述代码将引发错误:“Child”中的“virtual void GrandParent::foo()”没有唯一的最终重写器
。
关于如何解决这个问题有什么想法吗?
最佳答案
这是告诉你你的设计是错误的语言。确实如此。继承反射(reflect)了“is-a”关系。不是“有一个”。
解决方案是使用组合而不是继承。我想举一个例子,但完全不清楚你真正想要完成什么,也想不出任何合理的例子。
关于c++ - 有没有办法使用 using 声明来解析 "final overrider ambiguity"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54257546/