考虑代码
struct Base{}; struct Derived: public Base{}; struct A: public Base{}; struct B: public A,public Base{}; struct C: public A,public Derived{}; // why no ambiguity here? int main() {}
编译器(g 5.1)警告
warning: direct base
'Base'
inaccessible in'B'
due to ambiguitystruct B: public A,public Base{};
我明白这一点,基地在B.
>为什么C没有警告? C和C都不继承,它们都继承自Base?
>为什么添加虚拟
struct Derived: virtual Base{};
结果现在B和C发出警告,生活在Wandbox
warning: direct base
'Base'
inaccessible in'B'
due to ambiguitystruct B: public A,public Base{};
warning: direct base
'Base'
inaccessible in'C'
due to ambiguitystruct C: public A,public Derived{};
解决方法
在B中,不可能直接引用继承的Base子对象的成员.考虑:
struct Base { int x; }; struct B: public A,public Base { void foo() { int& x1 = A::x; // OK int& x2 = x; // ambiguous // no way to refer to the x in the direct base } };
在C这不是一个问题.可以使用限定名称来引用这两个x:
struct C: public A,public Derived { void foo() { int& x1 = A::x; // OK int& x2 = Derived::x; // OK } };
所以你得到的警告是一个直接的基地也是通过另一个路径继承的唯一有用的.
对于你的第二个问题,我无法用g -5.1重现Coliru上的C的警告.