在 CPP 文件中使用命名空间作为函数定义的前缀是否是一种好的做法

Is it a good practice to prefix the function definition with namespace in CPP files?

本文关键字:是否是 前缀 一种 定义 文件 CPP 命名空间 函数      更新时间:2023-10-16
// classone.h
namespace NameOne
{
class ClassOne
{
public:
    ...
    void FuncOne();
    ...
};
}
// *** Method 1 *** 
// classone.cpp
namespace NameOne // always define member functions inside the namespace
{
void ClassOne::FuncOne()
{ ... }
}
// *** Method 2 *** 
// classone.cpp
void NameOne::ClassOne::FuncOne() // always prefix the namespace
{ ... }

问题>我已经看到了两种处理 CPP 文件中命名空间的方法。在大型项目中哪种方法更好(即方法 1 或方法 2(

谢谢

如果它不在头文件中,只要你保持一致,就没关系。我个人更喜欢第一种方法,因为当您读取函数名称时,命名空间并不那么相关。

这是我

使用 .
using namespace X 的唯一情况我认为这是一个好的用法(但我仍在考虑它(,但愿意听到其他观点。

在文件栏中.cpp

// Bar in namespace Foo
#include "Bar.h"
// Only do this for the class I am defining
using namespace Foo;
Bar::Bar()
{
}
void Bar::stop()
{
}
// etc

我一直在体验:

// Bar in namespace Foo
#include "Bar.h"
// Only do this for the class I am defining
using Foo::Bar;
Bar::Bar()
{
}
void Bar::stop()
{
}
// etc
我想

这在很大程度上取决于您自己的个人喜好,除此之外,还取决于您编写代码的代码库中已经使用的内容。

我更喜欢添加using namespace NameOne.方法 1 增加缩进,方法 2 使声明更长,但这只是个人意见。只需在代码(和代码库(中保持一致即可。

我敢肯定,我记得在引入命名空间的时候读到C++方法2是最好的方法,当然比方法1更受欢迎,这就是我一直使用的。

使用命名空间的原因通常是将类/方法收集在具有一致功能的组/包中,以便它们与其他库或命名空间中的定义(字面上和功能上(不一致。

因此,我更喜欢在 cpp 文件中using namespace Foo,因为大多数时候我引用同一命名空间中的不同类。如果我需要使用另一个命名空间中的类,我肯定会使用Foo2::后缀。它保持实现的命名空间与其他命名空间之间的距离。