Putting class static members definition into cpp file — technical limitation?

后端 未结 2 1571
忘掉有多难
忘掉有多难 2021-01-14 02:10

one of my \"favorite\" annoyance when coding in C++ is declaring some static variable in my class and then looking at compilation error about unresolved static variable (in

相关标签:
2条回答
  • 2021-01-14 02:20

    First, from compiler's point of view, this is perfectly reasonable. Why redundant keyword where it is not needed?

    Second, I'd recommend against static members in C++. Before everybody jumps, I will try to explain.

    Well, you are not going to have any public static data members (very rarely useful). In any case, most classes have their own CPP file. If so, a static global, IMO is preferable over a private static member for reasons of dependency reduction. Unlike non-static private data, the static ones are not part of the interface, and there's very little reason why should the user of the h file ever have to recompile, or at all see these members.

    0 讨论(0)
  • 2021-01-14 02:37

    Well, this is just the way it works. You've only declared the static member in the .h file. The linker needs to be able to find exactly one definition of that static member in the object files it links together. You can't put the definition in the .h file, that would generate multiple definitions.

    UPDATE: C++17 can solve this with an inline variable.

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