开发者

Namespace in definition and implementation

If one has a header file, let's say "test.h" including开发者_StackOverflow中文版

namespace test
{
   enum ids
   {
      a = 1,
      b = 2,
      c = 3,
      d = 30
   };

   char *names[50];
};

and a source file, "test.cc" basically only including

test::names[test::a] = "yum yum";
test::names[test::c] = "pum pum";
// ...

Wouldn't it make more sense to wrap the implementation inside the namespace, too?

I'd say it would, as it's after all the implementation of the header file, so it would make sense to include the implementation in the same namespace as the header without manually prefixing every variable with test::, and prefix when using values from the outside.

This is the opinion of a C++ rookie, what would the smarter people say here?


You can specify the namespace in test.cc as well. To do this, you would do something like:

#include "test.h"

namespace test
{
    ...
    names[a] = "yum yum"; 
    names[c] = "pum pum"; 
    ...
}

You could alternately use using as in:

#include "test.h"

using test;

...
names[a] = "yum yum"; 
names[c] = "pum pum"; 
...

I generally use the first method.


I don't think it really matters, and I dont think there is global standard one way or the other. The important thing is to stay consistent with the rest of your codebase and do it the same way.

Personally, I prefer to wrap my implementation in the namespace like so:

namespace test
{
    names[a] = "yum yum"; 
    names[c] = "pum pum"; 
}

This seems to communicate to me that I am defining and implementing the test namespace, and not just "using" it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜