【发布时间】:2015-07-14 04:48:28
【问题描述】:
请考虑以下代码:
struct A
{
void f()
{
}
};
struct B1 : A
{
};
struct B2 : A
{
};
struct C : B1, B2
{
void f() // works
{
B1::f();
}
//using B1::f; // does not work
//using B1::A::f; // does not work as well
};
int main()
{
C c;
c.f();
return 0;
}
我恳请您不要复制粘贴有关如何解决菱形问题(“使用虚拟继承”)的标准回复。我在这里要问的是为什么在这种情况下使用声明不起作用。确切的编译器错误是:
In function 'int main()':
prog.cpp:31:6: error: 'A' is an ambiguous base of 'C'
c.f();
我从这个例子中得到了一个使用声明应该起作用的印象:
struct A
{
void f()
{
}
};
struct B
{
void f()
{
}
};
struct C : A, B
{
using A::f;
};
int main()
{
C c;
c.f(); // will call A::f
return 0;
}
【问题讨论】:
-
你需要 a::f 作为虚拟方法来覆盖它
-
我没有覆盖任何东西。我躲起来了。
-
可能:没有B1::f(名称解析为A::f),因此你有两个A::f(一个在B1,一个在B2)
-
@0x499602D2:删除
C::f定义。 -
再说一遍,你是一个在巨大大多数情况下是净收益的规则的不幸受害者。
标签: c++ inheritance subclass using-directives diamond-problem