Why shouldn't I put “using namespace std” in a header?

烈酒焚心 提交于 2020-01-09 11:56:09

问题


Someone once hinted that doing this in a header file is not advised:

using namespace std;

Why is it not advised?

Could it cause linker errors like this: (linewrapped for convenience)

error LNK2005: "public: __thiscall std::basic_string<char,struct 
std::char_traits<char>,class std::allocator<char> >::
~basic_string<char,struct std::char_traits<char>,class std::allocator<char> > 
(void)" (??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ) 
already defined in tools.lib(Exception.obj) 

回答1:


Because it forces anyone who uses your header file to bring the std namespace into global scope. This could be a problem if they have a class that has the same name as one of the standard library classes.




回答2:


If the file gets included elsewhere the compilation unit will implicitely get the using directive. This can lead to confusing errors when names overlap.



来源:https://stackoverflow.com/questions/3186226/why-shouldnt-i-put-using-namespace-std-in-a-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!