2

3.4.1/6 中的示例

namespace A {
   namespace N {
      void f();
   }
}
void A::N::f() {
   i = 5;
   // The following scopes are searched for a declaration of i:
   // 1) outermost block scope of A::N::f, before the use of i
   // 2) scope of namespace N
   // 3) scope of namespace A
   // 4) global scope, before the definition of A::N::f
}

以下代码基于此示例。请注意,它会打印 1。如果我注释掉i = 1;它会打印 2。如果我再注释掉i = 2;它会打印 3,这表明无论 A::N::f 的最外层块范围是什么,如果您i在此范围上定义,编译器将在其他名称i之前找到该名称。

#include <iostream>

namespace A {
    int i = 2;
    namespace N {
        int i = 1;    
        void f();
    }
}


int i = 3;
void A::N::f() {
    std::cout << i << '\n';;
    // The following scopes are searched for a declaration of i:
    // 1) outermost block scope of A::N::f, before the use of i
    // 2) scope of namespace N
    // 3) scope of namespace A
    // 4) global scope, before the definition of A::N::f
}

int main()
{
    A::N::f();
}
4

1 回答 1

4

该短语没有在标准的其他地方使用,但我们可以安全地得出结论,它指的是该函数中最外层的块范围。也就是函数体的作用域。这是非常直观且不足为奇的。

这意味着i首先寻找具有名称的局部变量。

于 2014-04-12T19:23:24.940 回答