您的位置:首页 > 编程语言 > C语言/C++

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 我也是新手 :-)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: