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.