代码之家  ›  专栏  ›  技术社区  ›  Jookia

C++在源文件中使用命名空间

  •  5
  • Jookia  · 技术社区  · 15 年前

    假设我正在做一个项目,并且大多数项目都在一个名为project的命名空间中。我在名为MainProject的命名空间项目中定义了一个类。

    在源文件中,若要实现类,请执行“using namespace Project;”或将其包装在“namespace Project{…”。。。}“巢?

    4 回复  |  直到 15 年前
        1
  •  7
  •   Steve M    15 年前

    给出标题“n.h”:

    namespace n{
      extern void f();
    }
    

    以下 没有 f() 在命名空间中 n (从现在起,我称之为 n::f

    #include "n.h"
    using namespace n;
    
    void f(){ }
    

    如果你试图提及 n: :f个 n: :f个 :

    #include "n.h"
    void n::f(){ }
    

    #include "n.h"
    namespace n{
      void f(){ }
    }
    

    但是也有一个缺点,如果您键入了错误的名称或签名,您将向名称空间添加一个新函数并离开 void n::f()

    当涉及到类时,情况就有些不同了:

    namespace n{
      class c{
        void f();
      };
      extern c operator + (const c&, const c&); // I'll use Matthieu M.'s example
    }
    

    不会有事的,因为没有全球性的 c

    #include "n.h"
    using namespace n;
    void c::f(){ }
    

    但如果您尝试添加两个c,则以下操作将导致链接时间错误,原因与第一次尝试定义 n::f() :

    #include "n.h"
    using namespace n;
    c operator + (const c &a, const c &b){ /* blah blah */ } // define global +
    

    ::c::f 已定义):

    class c{ // a global c, defined in some header somewhere
      void f();
    };
    
    #include "n.h"
    using namespace n;
    void c::f(){ } // define the global c::f (a possible redefinition) and n::c::f remains undefined!
    
        2
  •  3
  •   Björn Pollex    15 年前

    两种方法都很好,这实际上是一个品味问题(或命名冲突)。我通常都不这样做,只在需要的地方预先放置名称空间。

        3
  •  2
  •   Chubsdad    15 年前

        4
  •  1
  •   Matthieu M.    15 年前

    有(微妙的)问题 using namespace xxx; 语法。其中名字冲突。。。

    一般来说,最好不要使用它。我建议重新打开名称空间,而不是在标识符前面加上名称空间名称,但这更多的是一个品味问题。

    // header
    namespace foo
    {
      struct Bar
      {
        explicit Bar(int i);
        int x;
      };
      Bar operator+(Bar lhs, Bar rhs);
    }
    
    // source
    #include "the header here"
    
    using namespace foo;
    
    Bar operator+(Bar lhs, Bar rhs)
    {
      return Bar(lhs.x + rhs.x);
    }
    

    这会引发编译错误。

    推荐文章