gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:01:09 25 4
gpt4 key购买 nike

以下代码会导致错误,因为它没有考虑 ::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;驻留在全局命名空间范围内,因此通过在全局范围内查找来考虑。

关于C++:在主函数与全局作用域中使用指令语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66649869/

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