【问题标题】:Use of "using namespace" when declaring that namespace声明命名空间时使用“使用命名空间”
【发布时间】:2014-11-12 05:11:15
【问题描述】:

假设我有以下文件:

// SomeClass.h
namespace Example
{
    class SomeClass
    {
        ...
        SomeClass someFunction();
        ...
    };

}

// SomeClass.cpp
Example::SomeClass Example::SomeClass::SomeFunction()
{
    ...
}

添加“使用命名空间示例”会有什么后果吗?在 SomeClass.h 中的命名空间之前,以消除在 Someclass.cpp 文件中添加“Example::”范围运算符的需要?即使没有结果,这会被认为是不好的编码习惯吗?

变化如下:

// SomeClass.h
using namespace Example;

namespace Example
{
    class SomeClass
    {
        ...
        SomeClass someFunction();
        ...
    };

}

// SomeClass.cpp
SomeClass SomeClass::SomeFunction()
{
    ...
}

【问题讨论】:

  • 我一直在 .cpp 文件中使用它。我还没有看到任何缺点。但是,我没有在 .h 文件中使用它们。请记住,在引入命名空间之前,您不能使用 using namesapce Example;
  • 没有考虑将其放入 .cpp,谢谢。
  • 正如 R Sahu 所说,不要在标题中添加using namespace。它污染了包含它的每个文件的全局命名空间(不好玩)。

标签: c++ namespaces coding-style


【解决方案1】:

不,请不要将using namespace ...; 放在全球区域。你可以这样做:

SomeClass.h

// using namespace Example; // never here please

namespace Example
{
    using namespace OtherExample; // this is okay (not global)

    class SomeClass
    {
        ...
        SomeClass someFunction();
        ...
    };

}

SomeClass.cpp

namespace Example // same as in .h
{
    using namespace OtherExample; // this is okay (not global)

    SomeClass SomeClass::SomeFunction()
    {
        ...
    }
}

而且我还建议像std:: 这样的潜在巨大命名空间从不即使在您自己的命名空间中也使用using namespace std;,因为它们只会拖入太多常见的符号名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2010-11-03
    相关资源
    最近更新 更多