C++: Namespaces — How to use in header and source files correctly?

前端 未结 5 1470
走了就别回头了
走了就别回头了 2021-01-30 00:42

Consider a pair of two source files: an interface declaration file (*.h or *.hpp) and its implementation file (*.cpp).

Let the

5条回答
  •  攒了一身酷
    2021-01-30 01:06

    Are there any differences between these two practices

    Yes. #1 and #2 are examples of a using-directive and a namespace definition respectively. They are effectively the same in this case but have other consequences. For instance, if you introduce a new identifier alongside MyClass::foo, it will have a different scope:

    #1:

    using namespace MyNamespace;
    int x;  // defines ::x
    

    #2:

    namespace MyNamespace {
      int x;  // defines MyNamespace::x
    }
    

    is one considered better than the other?

    #1 Pros: a little more terse; harder to accidentally introduce something into MyNamespace unwittingly. Cons: may pull in existing identifiers unintentionally.

    #2 Pros: more clear that definitions of existing identifiers and declarations of new identifiers both belong to MyNamespace. Cons: easier to unintentionally introduce identifiers to MyNamespace.

    A criticism of both #1 and #2 is that they are referring to an entire namespace when you probably only care about the definition of members of MyNamespace::MyClass. This is heavy-handed and it communicates the intent poorly.

    A possible alternative to #1 is a using-declaration which includes only the identifier you're interested in:

    #include "MyClass.h"
    using MyNamespace::MyClass;
    
    int MyClass::foo() { ... }
    

提交回复
热议问题