考虑代码
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)警告说
警告:直接基地'Base'
无法访问于'B'
由于含糊不清struct B: public A, public Base{};
我明白这一点,Base
重复于B
.
-
为什么没有警告C
?没有C
继承两者A
and Derived
,两者都继承自Base
?
-
为什么要添加virtual
struct Derived: virtual Base{};
results now in both B
and C
emitting warnings, live on Wandbox
警告:直接基地'Base'
无法访问于'B'
由于含糊不清struct B: public A, public Base{};
警告:直接基地'Base'
无法访问于'C'
由于含糊不清struct C: public A, public Derived{};
In 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
}
};
In C
这不是问题。两个都x
可以使用限定名称来引用:
struct C: public A, public Derived {
void foo() {
int& x1 = A::x; // OK
int& x2 = Derived::x; // OK
}
};
因此,您收到的警告只有在以下情况下才有意义:directbase也是通过另外一条路径继承的。
对于你的第二个问题,我无法重现警告C
在 Coliru 上使用 g++-5.1。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)