C ++ class uses constructor to initialize the differences between class tables and assignment in the constructor body

Source: Internet
Author: User

C ++ Primer:

 

// Constref. cpp: defines console applicationsProgram.
//

# Include "stdafx. H"

Class constref
{
Public:
Constref (int ii );

Int I;
Const int ci;
Int & Ri;
};

Constref: constref (int ii)
{
I = II;
Ci = II;
Ri = I;
}

// Constref: constref (int ii): I (ii), CI (I), RI (ii ){}

Int _ tmain (INT argc, _ tchar * argv [])
{
Constref B (5 );

Printf ("% d, % d, % d", B. I, B. CI, B. RI );
Return 0;
}

In this case, there is an error in writing. Error c2758: "constref: Ci": it must be initialized in the constructor base/member Initial Value Setting item list;
Constref: RI: Must be initialized in the constructor base/member Initial Value List;
Error c2166: Specify the const object with the left value;

 

However

Constref: constref (int ii)
{
I = II;
Ci = II;
Ri = I;
}

Replace constref: constref (int ii): I (ii), CI (I), RI (ii) {} correctly. Do you know why?

 

Remember: const objects can be initialized or referenced objects, but they cannot be assigned a value. Initialization must be completed before you start executing the constructor's function body. The only opportunity to initialize a const or referenced data member is in the constructor initialization list.

 

 

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.