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

查看:102
本文介绍了在头和源(cpp)中创建C ++命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在命名空间中包装头文件和cpp文件内容,或者只包含头文件内容,然后在cpp文件中使用命名空间,这是否有区别?

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 it won't conflict. Some prefer the first way and other prefer the second version. Both versions doesn't 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. Anyway doing that creates more confusion with or without using keyword.

这篇关于在头和源(cpp)中创建C ++命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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