Correct way to define C++ namespace methods in .cp

2019-01-12 18:06发布

Probably a duplicate, but not an easy one to search for...

Given a header like:

namespace ns1
{
 class MyClass
 {
  void method();
 };
}

I've see method() defined in several ways in the .cpp file:

Version 1:

namespace ns1
{
 void MyClass::method()
 {
  ...
 }
}

Version 2:

using namespace ns1;

void MyClass::method()
{
 ...
}

Version 3:

void ns1::MyClass::method()
{
 ...
}

Is there a 'right' way to do it? Are any of these 'wrong' in that they don't all mean the same thing?

8条回答
▲ chillily
2楼-- · 2019-01-12 18:54

I'm using version 4 (below) because it combines most of the advantages of version 1 (terseness of the resoective definition) and version 3 (be maximally explicit). The main disadvantage is that people aren't used to it but since I consider it technically superior to the alternatives I don't mind.

Version 4: use full qualification using namespace aliases:

#include "my-header.hpp"
namespace OI = outer::inner;
void OI::Obj::method() {
    ...
}

In my world I'm frequently using namespace aliases as everything is explicitly qualified - unless it can't (e.g. variable names) or it is a known customization point (e.g. swap() in a function template).

查看更多
beautiful°
3楼-- · 2019-01-12 18:57

All the ways are right, and each one has its advantages and disadvantages.

In the version 1, you have the advantage of not having to write the namespace in front of each function. The disadvantage is that you'll get a boring identation, specially if you have more than one level of namespaces.

In version 2, you make your code cleaner, but if you have more than one namespace being implemented in the CPP, one may access the other one's functions and variables directly, making your namespace useless (for that cpp file).

In version 3, you'll have to type more and your function lines may be bigger than the screen, which is bad for design effects.

There is also another way some people use it. It is similar to the first version, but without the identation problems.

It's like this:

#define OPEN_NS1 namespace ns1 { 
#define CLOSE_NS1 }

OPEN_NS1

void MyClass::method()
{
...
}

CLOSE_NS1

It's up to you to chose which one is better for each situation =]

查看更多
登录 后发表回答