考虑一个类 D
继承自两个类 B
和 C
,每个都继承了非虚拟类 A
.有一个方法f
在 A
,以及 B
中相同的命名方法隐藏方法 A
.我要拨打A::f()
来自 B
-基类 D
对象如下:
struct A { void f() {} };
struct B : A { void f() {} };
struct C : A {};
struct D : B, C {};
int main() { D{}.B::A::f(); }
不幸的是,它只适用于 MSVC,而 GCC 和 Clang 都会产生错误:error: 'A' is an ambiguous base of 'D'
演示:https://gcc.godbolt.org/z/jY3v876hK它看起来像 GCC/Clang 接受但完全忽略
B::
B::A::f()
中的前缀.他们按照标准这样做是否正确?
最佳答案
Are they right in doing so according to the standard?
是的。
A::
中的嵌套名称说明符, B::A
, 或 D::B::A
都用于相同的目的,命名类 A
.[basic.lookup.classref]
4 If the id-expression in a class member access is a qualified-id of the form
class-name-or-namespace-name::...
the
class-name-or-namespace-name
following the.
or->
operator is first looked up in the class of the object expression ([class.member.lookup]) and the name, if found, is used. Otherwise it is looked up in the context of the entire postfix-expression.
嵌套名称说明符不命名成员的“路径”,它命名了
D
的基数。 .并命名 A
导致歧义。
关于c++ - 如何从C++中两次继承的基类调用隐藏方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69003592/