多重继承会导致虚假的模糊虚拟函数重载

问题描述 投票:3回答:1

在此示例中,从库提供类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吗?

c++ polymorphism overloading virtual-functions
1个回答
3
投票

您可以这样做:

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

最新测试为wandbox gcc,它可以正常编译。我认为函数重载也是这种情况,一旦重载,就无法在没有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

© www.soinside.com 2019 - 2024. All rights reserved.