C++:在主函数与全局作用域中使用指令语句

C++: using directive statement in main function Vs global scope

以下代码会导致错误,因为它没有在全局范围内考虑 ::x

#include<iostream>
namespace nspace
{
    int x = 2;
}
int main()
{
    using namespace nspace;
    std::cout << ::x; //error: ‘::x’ has not been declared
    return 0;
}

以下代码导致输出 2 没有任何编译错误。

#include<iostream>
namespace nspace
{
    int x = 2;
}
using namespace nspace;
int main()
{
    std::cout << ::x; // Outputs 2
    return 0;
}

我的印象是,如果我们在 main 函数中使用 using 指令与在全局范围内使用 using 指令,就 main 函数而言是一样的。对于 main 函数,两者都应该在全局范围内引入 nspace::x。两者都应该导致相同的行为。但是上面的代码与我的理解相矛盾。

因此,如果您能向我指出一些标准中阐明上述行为的文本,那将会很有帮助。

[namespace.qual]/1:

Qualified name lookup in a namespace N additionally searches every element of the inline namespace set of N ([namespace.def]). If nothing is found, the results of the lookup are the results of qualified name lookup in each namespace nominated by a using-directive that precedes the point of the lookup and inhabits N or an element of N's inline namespace set.

在第一种情况下,using namespace nspace; 位于 main 函数内部的块范围内,因此不予考虑。

在第二种情况下,using namespace nspace;驻留在全局命名空间范围内,因此在全局范围内查找时会考虑它。