c++ - 如何从C++中两次继承的基类调用隐藏方法?

标签 c++ language-lawyer multiple-inheritance

考虑一个类 D继承自两个类 BC ,每个都继承了非虚拟类 A .有一个方法fA ,以及 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/

相关文章:

c++ - 如何摆脱 -Wpointer-arith

c++ - 无法使用 SDL_LoadBMP 加载图像

c++ - 将 xvalues 转换为 lvalues 以传递给函数是否定义明确?

c# - C#或者底层的CLR真的不支持多重继承吗?

c++ - 在 Const char string[] 上使用字符串函数

c++ - 如何让一个类(class)成员保持未构造状态,以便以后使用 placement new 进行构造

c++ - 这个变量将如何初始化?

c++ - 为什么带逗号的三元运算符在真实情况下只计算一个表达式?

python - 结合多重继承使用元类的类型错误

c++ - C++中同时继承抽象类和类实现