在标头和源代码 (cpp) 中创建 C++ 命名空间 [英] Creating a C++ namespace in header and source (cpp)

查看:112
本文介绍了在标头和源代码 (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++ 命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆