gpt4 book ai didi

c++ - "using namespace"在 C++ 中是可传递的吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:14:34 26 4
gpt4 key购买 nike

令我惊讶的是,以下代码在 VC++ 2017 上编译并打印“X”:

#include <string>
#include <iostream>


namespace A {
using namespace std;
}

namespace B {
using namespace A;
}

namespace C {
using namespace B;
string a;
}

int main()
{
C::a = "X";
std::cout << C::a;
return 0;
}

看起来 using namespace std 从命名空间 A 通过命名空间 B 进入命名空间 C。

这是 Visual C++ 中的错误还是符合语言规范?

我曾预计 using namespace std 在封闭范围的末尾结束,也就是在命名空间 A 定义的末尾。

编辑:据我所知,对 this question 的公认答案也回答了我的问题。但是那篇文章更多的是关于匿名命名空间,而这篇文章是关于 using 命名空间指令的传递性。所以我认为这是一个更好的例子,这个问题也有道理。

最佳答案

是的:

[C++14: 7.3.4/4]: For unqualified lookup (3.4.1), the using-directive is transitive: if a scope contains a using-directive that nominates a second namespace that itself contains using-directives, the effect is as if the using-directives from the second namespace also appeared in the first. [..]

所以,编译器是正确的; using namespace 有效地将名称导入封闭的命名空间:

[C++14: 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. [..]

这里的“范围”是命名空间的范围;范围的内容不会仅仅因为遇到 } 就消失。不过,熟悉 block 作用域有时会让您有这种感觉。

关于c++ - "using namespace"在 C++ 中是可传递的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48830482/

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