C++ 中统一用 using namespace std; 有何弊端?
2015-09-24 23:48
423 查看
引用:http://www.zhihu.com/question/27920133
写程序时我都是统一用using namespace std;而代替分明声明std::cout,std::cin等,请问这样做有什么弊端?
Generally speaking, the using declaration is safer to use than a using directive because it shows exactly what names you are making available. And if the name conflicts with a local name, the compiler lets you know. The using
directive adds all names, even ones you might not need. If a local name conflicts, it overrides the namespace version, and you aren’t warned. Also, the open nature of namespaces means that the complete list of names in a namespace might be spread over several
locations, making it difficult to know exactly which names you are adding. C++ Primer Plus
用了using namespace std, 就有许多 cout,cin 之外的函数都用 std:: 了,很可能和你定义的函数的名字重复。为了安全起见别这么做。比如,如果你起初不知道 std 里有 endl,然后就用了using namespace std,同时你又定义了int endl,那么这两个函数就重复了。我也是新手,答的不好请改正。
多个文件可能会重复定义冲突了。一般直接加 std 比较安全 using namespace std 是把整个标准库加载进来,标准库是非常大的,保不准你定义个什么就会和标准库里面的冲突,所以使用 std 指明是标准库比较安全。ps 我也是新手 :-)
写程序时我都是统一用using namespace std;而代替分明声明std::cout,std::cin等,请问这样做有什么弊端?
Generally speaking, the using declaration is safer to use than a using directive because it shows exactly what names you are making available. And if the name conflicts with a local name, the compiler lets you know. The using
directive adds all names, even ones you might not need. If a local name conflicts, it overrides the namespace version, and you aren’t warned. Also, the open nature of namespaces means that the complete list of names in a namespace might be spread over several
locations, making it difficult to know exactly which names you are adding. C++ Primer Plus
用了using namespace std, 就有许多 cout,cin 之外的函数都用 std:: 了,很可能和你定义的函数的名字重复。为了安全起见别这么做。比如,如果你起初不知道 std 里有 endl,然后就用了using namespace std,同时你又定义了int endl,那么这两个函数就重复了。我也是新手,答的不好请改正。
多个文件可能会重复定义冲突了。一般直接加 std 比较安全 using namespace std 是把整个标准库加载进来,标准库是非常大的,保不准你定义个什么就会和标准库里面的冲突,所以使用 std 指明是标准库比较安全。ps 我也是新手 :-)
相关文章推荐
- C++Primer第五版 练习11.8(解答)
- C++Primer第五版 练习11.7(解答)
- C++Primer第五版 11.2.1节练习
- C和指针 (学习之旅)
- 关于C++中new的一些理解
- C++编程思想学习笔记---第12章 运算符重载
- C++ 项目经验总结:程序严谨性(一)
- 【C++】动态内存分配
- c++设计模式-----命令模式
- C语言的第不知道多少天
- C/C++ 之 ‘++’、‘+’、‘+=’、‘-’、‘()’、‘--’ 操作符的重载实现重载
- C/C++ 之 操作符重载
- C/C++结构体字节对齐详解
- C++基础复习---5(内联函数 重载函数)
- C++基础复习---4(内存分配)
- c++基础复习-----3(位运算)
- C++基础复习-----2(const 与static)
- C语言中的值传递和引用传递(地址传递)
- C++基础中易混淆点
- C++基础复习---1(函数指针,指针函数)