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();
}