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

标签 c++ class scope name-lookup injected-class-name

根据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/

相关文章:

c++ - 为什么在另一个案例中允许在 block 内使用 case 语句?

Java:我该如何解决错误: "implicit super constructor is undefined"

JavaScript Angular Controller 从另一个 Controller 的范围中获取值

c++ - C++ 中的变量作用域

java - java中有没有办法限制一个包对其他包的可见性

python - 为什么 Python +=(加等于)运算符不修改内部函数中的变量?

c++ - 为什么 g++ 声明某些 valarray<double> o 有 "no matching function for call cbegin(o)"?

c++ - 安全的 C++ 编码实践

c++ - 查找线程之间的最小队列大小

ruby - 在循环中创建类对象