当 Injected-Class-Name 发生时会发生什么? (C++)

What happens when Injected-Class-Name occurs? (C++)

根据https://en.cppreference.com/w/cpp/language/injected-class-name

In a class scope, the name of the current class is treated as if it were a public member name; this is called injected-class-name. The point of declaration of the name is immediately following the opening brace of the class definition.

int X;
struct X {
    void f() {
        X* p; // OK. X refers to the injected-class-name
        ::X* q; // Error: name lookup finds a variable name, which hides the struct name
    }
};

那么代码中到底发生了什么? X* p是不是变成了X::X* p

在全局命名空间中搜索此限定名称 ::X。由于没有具有这样名称的类型(变量声明隐藏了类型 struct X),编译器发出错误。

您可以使用详细的名称,例如

int X;
struct X {
    void f() {
        X* p; // OK. X refers to the injected-class-name
        struct ::X* q; // OK. elaborated name struct ::X
    }
};

So what is really happening in the code? Is X* p turned into X::X* p?

基本上。名称查找规则从最窄的范围开始。当您在 f 中执行 X* p; 时,会在 f 的范围内查找但没有找到任何内容。然后它检查 X 的范围,因为 f 的范围是 X。它找到 X 因为它被注入到 class 范围所以它停在那里并且你得到 class 类型。

当你执行 ::X* q; 然后 ::X 说在全局命名空间中查找 X,并且找到了一个变量,而不是类型,所以你得到一个错误。