尽量不要使用using namespace std;
《C Primer Plus (第六版 中文版 人民邮电出版社)》第九章:内存模型和名称空间 第328页:
有关using编译命令和using声明,需要记住的一点是,他们增加了名称冲突的可能性。
C Primer Plus (第六版 中文版 人民邮电出版社)》第九章:内存模型和名称空间 第329页:
一般说来,使用using命令比使用using编译命令更安全,这是由于它只导入了制定的名称。如果该名称与局部名称发生冲突,编译器将发出指示。using编译命令导入所有的名称,包括可能并不需要的名称。如果与局部名称发生冲突,则局部名称将覆盖名称空间版本,而编译器并不会发出警告。另外,名称空间的开放性意味着名称空间的名称可能分散在多个地方,这使得难以准确知道添加了哪些名称。
...
...
然而名称空间的支持者希望有更多的选择,既可以使用解析运算符面也可以使用using声明,也就是说,不要这样做:
using namespace std; // avoid as too indiscriminate(随意)
而应这样做:
int x;
std::cin >> x ;
std::cout << x << std::endl;
或者这样做:
using std::cin;
using std::cout;
using std::endl;
int x;
cin >> x;
cout << x << endl;
《C Primer Plus (第六版 中文版 人民邮电出版社)》附录I: 转换为ISO标准的C++ 第914页:
名称空间有助于组织程序中使用标识符,避免名称冲突。由于标准库是使用性的头文件组织实现的,它将名称放在std名称空间中,因此使用这些头文件需要处理名称空间。
...
...
然而,不管需要与否,都导出名称空间中的所有名称 ,是与名称空间的初衷背道而驰的。
在Steve Donovan 《C by Example》中写到:
However, some people feel strongly that using namespace std cases namespace pollution because everything is dumped into the global namespace, which is what namespaces were designed to prevent. You need to understand the implications of using namespace std, and you need to recognize that there is one case where it always a bad idea.
而在国外的论坛StackOverflow
对于What requires me to declare “using namespace std;”?
Péter Török给出了这样的解释:
However,
using namespace std;
is considered a bad practice because you are practically importing the whole standard namespace, thus opening up a lot of possibilities for name clashes. It is better to import only the stuff you are actually using in your code, like
using std::string;
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
