c++ - 有没有办法使用 using 声明来解析 "final overrider ambiguity"?

标签 c++ abstract-class multiple-inheritance using virtual-functions

我正在尝试使用虚拟类方法解决可怕的菱形继承(钻石问题)。

让我们首先考虑具有最终虚方法特性的多重继承情况。 由于存在 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/

相关文章:

c++ - 调试断言失败!表达式 : _pFirstBlock == pHead

java - 强制子类实现抽象子类

c# - 在 C# 中可以使用接口(interface)实现多重继承吗?

c# - 多重继承?

c++ - C++中多重继承对象的内存布局

c++ - 错误 C2512 但我有可用的默认构造函数

c++ - 使用 GCC switch case 范围,是否可以构建范围为 [A-Za-z] 的单个 case?

c# - 在抽象通用测试类中定义单元测试

c++ - 多线程程序卡在优化模式但在-O0下正常运行

c++ - 函数定义上的纯说明符