开发者

Using "namespace foo {" instead of explicitly qualifying outside of header files [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect ans开发者_高级运维wers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 11 years ago.

If a function is declared as such:

namespace foo {
    void bar();
}

Most people define the function like this:

void foo::bar() {
    ...
}

However I like to do it this way:

namespace foo {
    void bar() {
        ...
    }
}

I prefer this style because its saves me from always retyping foo::, which is often tedious in function parameters that accept types declared in that same namespace. Plus its easier to rename the whole namespace.

I'm wondering why I almost never see my style in other peoples code, are there any disadvantages too it, besides the additional indentation level (and you don't even have to indent namespaces)?


If you use the foo::bar form, and accidentally define the function with incorrect arguments, you will get a compiler error. If you put the definition in a namespace in the source file, different arguments will simply result in a different function being defined. You won't get an error until you try to link with code which uses your function (which in the case of a DLL, may not be until runtime).


Finding foo::bar on the command-line is not easy. Having foo::bar to grep for is quite nice.


namespace foo {
    void bar {
        ...
     }
 }

Can cause multiple definition error. This error comes at link time.

Say that you have put this namespace foo in a header file and defined the function bar() inside it. Now, when you include this header file to multiple .cpp file, multiple definitions of foo::bar() will be generated. Thus, linker error.

[Note: I assume that in the 1st case, you are defining foo::bar in a .cpp file.]

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜