c++ - 名称查找说明

标签 c++ c++11 name-lookup

$10.2/4- "[ Note: Looking up a name in an elaborated-type-specifier (3.4.4) or base-specifier (Clause 10), for instance, ignores all nontype declarations, while looking up a name in a nested-name-specifier (3.4.3) ignores function, variable, and enumerator declarations."

在描述名称查找时,我发现本节中的这个语句非常困惑。

void S(){}

struct S{
   S(){cout << 1;}
   void f(){}
   static const int x = 0;
}; 

int main(){ 
   struct S *p = new struct ::S;  // here ::S refers to type
   p->::S::f();

   S::x;  // base specifier, ignores the function declaration 'S'

   ::S(); // nested name specifier, ignores the struct declaration 'S'.
   delete p;
} 

我的问题:

  1. 我对规则的理解是否正确?

  2. 为什么 ::S 在执行 new 的行中自动处理为结构 S,而在最后一行 ::S 表示全局命名空间中的函数 S

  3. 这是否表明文档中存在歧义,还是我又要远离 C++ 标准文档了?

最佳答案

Q1:我觉得是。

问题 2:与 C 的兼容性。当您在 C 中声明一个 struct 时,标记名称就是标记名称。为了能够以独立的方式使用它,您需要一个 typedef。在 C++ 中,您不需要 typedef,这让生活更轻松。但是 C++ 规则由于需要能够导入已经存在的 C header 而变得复杂,这些 header “重载”了带有函数名称的标记名称。典型的例子是 Unix stat() 函数,它使用 struct stat* 作为参数。

Q3:标准阅读通常是相当困难的……你需要知道没有其他地方可以修改你正在阅读的内容。知道如何做到这一点的人是语言律师并不奇怪......

关于c++ - 名称查找说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4094253/

相关文章:

c++ - 模板函数中默认参数的实例化点

c++ - 运算符重载 clang++ 和 g++ 不同的输出

c++ - GCC非法指令

c++ - 对于 C++ 中的名称别名,应该优先使用而不是定义

c++ - 生成不同格式的图像字节数据

c++ - 合并 K 排序链表中的循环

c++ - txt 文件的输入在第二次读取/传递时不匹配 (C++)

c++ - 在匿名类中返回* this时, 'auto'返回类型是什么类型?

用 auto 定义的变量的 C++11 类型

c++ - 什么是 "Argument-Dependent Lookup"(又名 ADL,或 "Koenig Lookup")?