int main() { const int ival=1024; const int &refval=ival;//ok both reference and object are const //const引用是指向const对象的引用 //因为不能对ival修改,因此不能通过refval来修改ival //int &ref2=ival;//error:nonconst reference to a const object //是普通非const引用,因此可修改ref2所指对象,为阻止,需要规定普通引用不能绑定const对象 system("pause"); } ---------------------------------------------------------------------------------------------------------- int main() { int i=1; //double &d=i;//error:cannot convert from 'int' to 'double &' //legal for const references only const int &a=i; const int &b=2;//const引用可以初始化为不同类型的对象或者初始化为右值,如字面常量值 const int &c=i+1; const double &d=i;
//double temp=i; //creat temporary double from the int
//const double &d2=temp;//bind d to that temporary
double &d2=i;//d2不为const,可对其赋一新值,这样做不会修改i,而是修改了temp,
//仅允许const引用绑定到需要时使用完全避免了这个问题 system("pause"); }