gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:39:05 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com