gpt4 book ai didi

c++ - c++ using 指令的范围

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:20:06 24 4
gpt4 key购买 nike

来自 c++11 标准的第 7.3.4.2 节:

A using-directive specifies that the names in the nominated namespace can be used in the scope in which the using-directive appears after the using-directive. During unqualified name lookup (3.4.1), the names appear as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace. [ Note: In this context, “contains” means “contains directly or indirectly”. —end note ]

第二句和第三句到底是什么意思?请举例说明。

这是我试图理解的代码:

namespace A
{
int i = 7;
}
namespace B
{
using namespace A;
int i = i + 11;
}
int main(int argc, char * argv[])
{
std::cout << A::i << " " << B::i << std::endl;
return 0;
}

它打印“7 7”而不是我期望的“7 18”。

抱歉打错了,程序实际上打印了“7 11”。

最佳答案

代码中的 using 语句是无关紧要的。当评估 B::i 的初始化程序时,B::i 已经在范围内。您可以通过删除 using 语句来简单地证明这一点;您的代码应该可以正常编译和运行。在任何情况下,B::i 的值最终都是未定义的,因为它依赖于一个未初始化的值(即 B::i 在初始化器被初始化时的值)评估)。

关于c++ - c++ using 指令的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12516476/

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