在 CPP 文件中使用命名空间作为函数定义的前缀是否是一种好的做法
Is it a good practice to prefix the function definition with namespace in CPP files?
// 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::
后缀。它保持实现的命名空间与其他命名空间之间的距离。
相关文章:
- C++LDAP检查用户是否是特定组的成员
- 检查某些类型是否是模板类 std::optional 的实例化
- 将错误返回给调用方而不是立即在 C++ 中抛出错误是否是一种好的做法
- 如何检查模板专用化是否是基本模板的子类?
- 如何检查变量是否是C++中的地图?
- C++ Chrono 确定一天是否是周末?
- 将相同共享指针的副本存储在不同的向量中是否是一种好的做法?
- 使用类在C++中存储和列出变量/方法是否是一种好的做法
- 代码在 CodeSignal 中工作不正确。不确定这是否是我的代码缺陷
- 如果 C 函数仍然可以间接执行(通过回调函数),那么将它声明为静态函数是否是一种不好的做法?
- MFC 中的窗口消息管理:添加基类调用是否是强制性的?
- 检查 n2 是否是 n1 的倍数后结果错误,但根本没有错误
- C ++:检查它是否是类中的数字
- 传递给放置 new 的指针是否是指向其对象表示形式的非 UB 指针?
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 从 std::string 到 std::array<char,size> 的 memcopy 额外数据是否是一种未定义的行为?
- 在 CPP 文件中使用命名空间作为函数定义的前缀是否是一种好的做法
- 如何搜索字符串是否是存储在集合中的字符串的前缀
- 找出(在c++中)二进制数是否是另一个二进制数的前缀
- 检查一个字符串是否是另一个字符串的前缀