【问题标题】:Why shouldn't I put "using namespace std" in a header?为什么我不应该将“使用命名空间标准”放在标题中?
【发布时间】:2010-07-06 12:42:42
【问题描述】:

曾经有人暗示不建议在头文件中这样做:

using namespace std;

为什么不建议这样做?

会不会导致这样的链接器错误:(为方便起见,换行了)

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) 

【问题讨论】:

标签: c++ header-files using


【解决方案1】:

因为它强制使用您的头文件的任何人将std 命名空间带入全局范围。如果他们有一个与标准库类同名的类,这可能是个问题。

【讨论】:

    【解决方案2】:

    如果文件被包含在其他地方,编译单元将隐含地获取 using 指令。当名称重叠时,这可能会导致令人困惑的错误。

    【讨论】:

    • 它会导致这样的链接器错误:error LNK2005: "public: __thiscall std::basic_string,class std::allocator >:: ~basic_string,class std::allocator >(void)" (??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@ D@2@@std@@QAE@XZ) 已经在 tools.lib(Exception.obj) 中定义??
    • @Tony:您应该将此添加到问题中。使用适当的格式会更容易阅读。
    猜你喜欢
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 2011-08-29
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多