class ConstRef{public: ConstRef(int ii);//private: int i; const int ci; int &ri;};//ConstRef::ConstRef(int ii)//{// i = ii; // ok// ci = ii; // error:cannot assign to a const// ri = ii; // error:ri was never initialized//}// ok:explicitly initialize reference and const membersConstRef::ConstRef(int ii) :i(ii), ci(ii), ri(ii){};
只能通过构造函数的初始化列表来为const, reference or of a class type that does not have a default-constructor进行初始化。
引用初始化了吗?
ConstRef(int ii = 0);// defines the default constructor as well as one that takes a argumentConstRef crf;//or int i = 0;ConstRef crf(i);cout << crf.ri << endl;cout << crf.ci << endl;cout << crf.i << endl;//crf.ci = 10;// errorcrf.ri = 10; // no effectcout << crf.ri << endl; // print a undefine valuecout << crf.i << endl;//result:/*136093 // a undefined value 0 0 136093 // a undefined value 0*/ // ii is a local variable of ConstRef(int ii = 0)
must use conference type to initlialize conference argument
ConstRef::ConstRef(int& ii) :i(ii), ci(ii), ri(ii){};