根据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
?
最佳答案
So what is really happening in the code? Is X* p turned into
X::X*
p?
基本上。名称查找规则从最窄的范围开始。当你这样做
X* p;
在 f
正在查看 f
的范围,并没有找到任何东西。然后它检查 X
的范围自 f
范围为 X
.它找到 X
因为它被注入(inject)到类范围中,所以它停在那里,你得到了类类型。当你这样做
::X* q;
然后 ::X
说寻找 X
在全局命名空间中,并且找到了一个变量,而不是一个类型,所以你会得到一个错误。
关于c++ - 当 Injected-Class-Name 发生时会发生什么? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59956150/