在此示例中,从库提供类Foo
和Bar
。我的课程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
吗?
您可以这样做:
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