STL container [30]

Source: Internet
Author: User

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 (){/*.. */}//};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.