Possible duplicate:Defining static members in C ++
I work a bit in C ++ and I don’t understand how to use static fields in C ++, they seem to be useless. Please correct me.
I can not do it:
class AClass{ public: static int static_field = 0; };
And WHAT doesn't work.
class AClass{ public: static int static_field; }; int main(){ int AClass::static_field = 0; return 0; }
You must initialize static_field outside the scope of the main function.
int AClass::static_field = 0; int main(){ }
Actually, you were close.
You must move: int AClass::static_field = 0;outside main()so that it is global in the CPP file, preferablyAClass.cpp.
int AClass::static_field = 0;
main()
AClass.cpp.
, . main() , AClass::static_field , /.
AClass::static_field
PS: .
... , , . , . /, . , , , , .
:
class AClass{ public: static int static_field; }; int AClass::static_field = 0; int main(){ return 0; }
When you declare a static variable here, you declare that there will be one instance of this variable, common to all instances of the class.
Moving an ad outside the core function, like some of the other answers provided, is the right decision.
Here are some docs from msdn for the static keyword:
http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx
hope this helps