Creating a C++ namespace in header and source (cpp)(在标头和源代码 (cpp) 中创建 C++ 命名空间)
问题描述
在命名空间中包装头文件和 cpp 文件内容或仅包装头文件内容然后在 cpp 文件中执行 using namespace 有什么区别吗?
Is there any difference between wrapping both header and cpp file contents in a namespace or wrapping just the header contents and then doing using namespace in the cpp file?
我所说的差异是指任何可能导致问题或我需要注意的任何排序性能损失或稍微不同的语义.
By difference I mean any sort performance penalty or slightly different semantics that can cause problems or anything I need to be aware of.
例子:
// header
namespace X
{
class Foo
{
public:
void TheFunc();
};
}
// cpp
namespace X
{
void Foo::TheFunc()
{
return;
}
}
VS
// header
namespace X
{
class Foo
{
public:
void TheFunc();
};
}
// cpp
using namespace X;
{
void Foo::TheFunc()
{
return;
}
}
如果没有区别,首选形式是什么?为什么?
If there is no difference what is the preferred form and why?
推荐答案
命名空间只是一种破坏函数签名的方法,这样它们就不会发生冲突.有些人更喜欢第一种方式,而另一些人更喜欢第二种方式.这两个版本对编译时性能没有任何影响.请注意,命名空间只是一个编译时实体.
Namespace is just a way to mangle function signature so that they will not conflict. Some prefer the first way and other prefer the second version. Both versions do not have any effect on compile time performance. Note that namespaces are just a compile time entity.
使用命名空间出现的唯一问题是我们有相同的嵌套命名空间名称(即)X::X::Foo.无论是否使用关键字,这样做都会造成更多混乱.
The only problem that arises with using namespace is when we have same nested namespace names (i.e) X::X::Foo. Doing that creates more confusion with or without using keyword.
这篇关于在标头和源代码 (cpp) 中创建 C++ 命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在标头和源代码 (cpp) 中创建 C++ 命名空间
基础教程推荐
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- c++ STL设置差异 2022-01-01
