Index. cpp: 59: In-class initialization of static data member of non-integral type 'const string'
Index. cpp: 60: In-class initialization of static data member of non-integral type 'const string'
Index. cpp: 61: In-class initialization of static data member of non-integral type 'const string'
Static class members may not be initialized in a constructor
A common mistake is to initialize static class members inside the constructor body or a member-initialization list like this:
Class file {PRIVATE: static bool locked; private: file (); //}; file: file (): Locked (false) {}// error, static initialization in a member initialization list
Although compilers flag these ill-formed initializations as errors, programmers often wonder why this is an error. bear in mind that a constructor is called as frequently times as the number of objects created, whereas a static data member may be initialized only once because it is shared by all the class objects. therefore, you shoshould initialize static members outside the class, as in this example:
Class file {PRIVATE: static bool locked; private: file (){/*.. * //}; file: locked = false; // correct initialization of a non-const static member
Alternatively, for const static members of an integral type, the standard now allows in-class initialization:
Class Screen {PRIVATE: const static int pixels = 768*1024; // In-class initialization of const static integral typespublic: screen (){/*.. */}//};