double value =3.14159;double&ref_value = value;double&ref1;// error: 'ref1' declared as reference but not initializeddouble&ref2 =3.14159;// error: cannot bind non-const lvalue reference of type // 'double&' to an rvalue of type 'double'double&ref3 =3.14159* value;// error: cannot bind non-const lvalue reference of type // 'double&' to an rvalue of type 'double'int ival =1;double&iref = ival;// error: invalid initialization of reference of type // 'double&' from expression of type 'int'double&ref_ref_value = ref_value;
double value =3.14159;constdouble&ref_value = value;
value =1.0;// ref_value = 1.0
ref_value =3.0;// error: assignment of read-only reference 'ref_value'
还可以将常量引用绑定至类型匹配的表达式或者字面值:
constint&ref1 =1024;constint&ref2 = ref1 *2;
不允许将非常量引用绑定至常量对象,因为这将存在通过非常量引用修改常量对象的风险:
constint buffer_size =1024;int&ref_buffer_size = buffer_size;// error: invalid initialization of reference of // type 'int&' from expression of type 'const int'
指向 const 的指针
constdouble value =3.14159;constdouble*p_value =&value;double*p_value2 =&value;// error: invalid conversion from 'const double*' to 'double*'
double value =3.14159;double*const p_value =&value;
value =1.0;// value 为非常量,可以被修改*p_value =2.0;// value = 2.0,p_value 不是指向 const 的指针,可以用来改变 value 的值double sqrt2 =1.414;
p_value =&sqrt2;// error: assignment of read-only variable 'p_value'