Correct way to define C++ namespace methods in .cpp file

后端 未结 8 1432
你的背包
你的背包 2020-12-12 11:10

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

Given a header like:

namespace ns1
{
 class MyClass
 {
  void method();
 };
}
相关标签:
8条回答
  • 2020-12-12 12:06

    It turns out it's not only "coding-style matter". Num. 2 leads to linking error when defining and initializing a variable declared extern in header file. Take a look at example in my question. Definition of constant within namespace in cpp file

    0 讨论(0)
  • 2020-12-12 12:07

    I choose Num.3 (a.k.a. the verbose version). It's more typing, but the intent is exact to you and to the compiler. The problem you posted as-is is actually simpler than the real world. In the real world, there are other scopes for definitions, not just class members. Your definitions aren't very complicated with classes only - because their scope is never reopened (unlike namespaces, global scope, etc.).

    Num.1 this can fail with scopes other than classes - anything that can be reopened. So, you may declare a new function in a namespace using this approach, or your inlines could wind up being substituted via ODR. You will need this for some definitions (notably, template specializations).

    Num.2 This is very fragile, particularly in large codebases - as headers and dependencies shift, your program will fail to compile.

    Num.3 This is ideal, but a lot to type - what your intent is to define something. This does exactly that, and the compiler kicks in to make sure you've not made a mistake, a definition is not out of synch with its declaration, etc..

    0 讨论(0)
提交回复
热议问题