多重继承导致虚假的二义性虚函数重载函数、虚假、二义性虚

2023-09-04 22:51:24 作者:云雾

在本例中,类FooBar是从库中提供的。我的类Baz从两者继承。

struct Foo
{
    void do_stuff (int, int);
};

struct Bar
{
    virtual void do_stuff (float) = 0;
};

struct Baz : public Foo, public Bar
{
    void func ()
    {
        do_stuff (1.1f); // ERROR HERE
    }
};

struct BazImpl : public Baz
{
    void do_stuff (float) override {};
};

int main ()
{
    BazImpl () .func ();
}

我得到编译错误reference to ‘do_stuff’ is ambiguous,这在我看来是错误的,因为两个函数签名完全不同。如果do_stuff是非虚拟的,我可以调用Bar::do_stuff来消除它的歧义,但这样做会破坏多态并导致链接器错误。

我可以在不重命名对象的情况下调用func虚拟do_stuff吗?

推荐答案

cpp 多重继承与虚继承virtual 避免重复继承变量导致二义性

您可以这样做:

struct Baz : public Foo, public Bar
{
    using Bar::do_stuff;
    using Foo::do_stuff;
    //...
}

用最新的wandboxGCC测试,编译正常。我认为函数重载也是如此,一旦重载了一个函数,没有using就不能使用基类实现。

事实上,这与虚拟函数无关。以下示例具有相同的错误GCC 9.2.0 error: reference to 'do_stuff' is ambiguous

struct Foo
{
    void do_stuff (int, int){}
};

struct Bar
{
    void do_stuff (float) {}
};

struct Baz : public Foo, public Bar
{
    void func ()
    {
        do_stuff (1.1f); // ERROR HERE
    }
};

可能相关的question