可以在 C++ 中使用子 class 名称引用方法吗?

Can a method be referenced using a child class name in C++?

请考虑具有方法 f 的结构 A 和不重新定义 f 的继承结构 B。在这种情况下 B::f 指的是与 A::f.

相同的方法

是否允许使用 B::f 名称调用 A 对象的方法 f,如下例所示?

struct A { void f() {} };
struct B : A {};
int main() { A{}.B::f(); }

Clang 和 GCC 在这里发生分歧。 Clang 对程序没问题,而 GCC 打印错误:

error: 'B' is not a base of 'A'

演示:https://gcc.godbolt.org/z/Pn7jehzdP

哪个编译器符合标准?

Is it allowed to invoke the method f of an A object using B::f name as in the following example?

struct A { void f() {} };

struct B : A {};

int main() { A{}.B::f(); }

A{}.B::f() 尝试构建类型为 A 的对象。然后调用它的成员B::f这个错误,因为A对B一无所知

如果您想从派生的 class 调用基成员,通常您只需使用 D d; d.f();

在你的情况下,使用 B{}.A::f()
请注意,像这样调用基方法会破坏虚方法。

GCC 是正确的:[class.access.base]/6 要求指向 . 的左侧操作数的指针能够

implicitly converted to a pointer to the naming class of the right operand.

术语“命名 class”在 [class.access.general]/5 中定义;在您的示例中,它是 B,显然 A* 不能 隐式 转换为 B*.

规则的放置对于没有非public成员或继承的这种特殊情况是违反直觉的。