[英]C++ - Why isn't this structure of diamond inheritance cause an ambiguity?
I have scanned through dozens of multiple inheritance question but wasn't able to find an answer for this question.我已经扫描了数十个 inheritance 问题,但无法找到该问题的答案。
I understand why this won't compile:我明白为什么这不会编译:
struct B{
virtual void f(){
printf("B");
}
};
struct C1 : virtual B{
void f() override{
printf("C1");
}
};
struct C2: virtual B{
void f() override{
printf("C2")
}
};
struct D: C1,C2{
};
Because there is not way to determine which f
should be in B
's vtable.因为没有办法确定哪个
f
应该在B
的 vtable 中。
However, I was quite surprised to see that this code will compile:但是,我很惊讶地看到这段代码可以编译:
struct B{
virtual void f(){
printf("B");
}
};
struct C1 : virtual B{
void f() override{
printf("C1");
}
};
struct C2: virtual B{
};
struct D: C1,C2{
};
My (wrong) intuition was that we still have two path from D
to B
and in each one the last place f
is overridden is different - in one path it's in C1
and in one path it's in B
, but this does compile.我的(错误的)直觉是我们仍然有两条从
D
到B
的路径,并且在每一条中f
被覆盖的最后一个位置是不同的 - 在一条路径中它在C1
中,在一条路径中它在B
中,但这确实可以编译。
Why doesn't this cause an ambiguity?为什么这不会引起歧义?
Because C1::f1 overrides B::f1, it will be used in preference on any object that has a dynamic type of C1 or any subclass.因为 C1::f1 覆盖 B::f1,它将优先用于任何具有 C1 动态类型或任何子类的 object。
In the ambiguous case, While both C1::f1 and C2::f1 override B::f1, they do not override each other, so the ambiguity is between them -- the fact that they both override a common base function is irrelevant.在模棱两可的情况下,虽然 C1::f1 和 C2::f1 都覆盖了 B::f1,但它们不会相互覆盖,因此它们之间存在歧义——它们都覆盖了一个公共基础 function 的事实是无关紧要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.