Initialization of const member variables

Source: Internet
Author: User

Const member variable Initialization
Const member variables can only be initialized in the class constructor. The following compilation error is reported:

// Const. h # include <iostream> class cconst {public: cconst (); void

Print () {std: cout <"----" <cs <std: endl;} private:

Const int cs ;};
// Const. cpp # include "const. h" cconst: cconst () {}int main (int argc, char *

Argv []) {cconst * a = new cconst (); a-> print (); return 0 ;}


Error c2758: 'cs ': must be initialized in constructor

Base/member initializer list

Change const. cpp:


# Include "const. h" cconst: cconst () {cs = 0;} int main (int argc, char *

Argv []) {cconst * a = new cconst (); a-> print (); return 0 ;}

Still error:

Error c2758: 'cs ': must be initialized in constructor base/member

Initializer list

After it is changed to the following format, it is normal:


# Include "const. h" cconst: cconst (): cs (0) {// cs = 0;} int main (int argc,

Char * argv []) {cconst * a = new cconst (); a-> print (); return 0 ;}

Related Article

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.