Why does c++ class need to define static field(data member) outside the class scope? [duplicate]

StackOverflow https://stackoverflow.com/questions/11045919

سؤال

Possible Duplicate:
Initializing private static members
Why I can't initialize non-const static member or static array in class?

It is strange to me. Why not assume there is a static field at the global scope?

هل كانت مفيدة؟

المحلول

It has to be placed somewhere (in some object file), so linker could find it. If you have declaration of class with static filed in .h file and include this file in a few .cpp files, then it would be ambiguous, which object file should have place allocated for this filed.

Please also note, that primitive type const static field could be initialized in class declaration:

class Foo
{
    static const int n = 42;
};
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top