3.6 引用类型

来源:互联网 发布:mac退出后台程序 编辑:程序博客网 时间:2024/05/21 07:58


#include <iostream.h>int main(void){double dval = 1024;const int &ri = dval;cout << "dval=" << dval << endl;cout << "ri=" << ri << endl;double dval2 = 3.14159;// ri = dval2;/** ** Error 337: "3.6ref.c", line 11 # The left side of '=' must be a modifiable lvalue. **             ri = dval2; **             ^^          **/cout << "dval2=" << dval2 << endl;/** ** 用一个const 对象的地址来初始化一个引用 **/cout << "\n用一个const 对象的地址来初始化一个引用: " << endl;// const int ival = 1024;// 错误: 要求一个const 引用// int *&pi_ref = &ival;/** ** Error 440: "3.6ref.c", line 27 # Cannot initialize 'int *&' with 'const int *'. **             int *&pi_ref = &ival; **                            ^^^^^  **/  // 仍然错误 // const int *&pi_ref = &ival;/** ** Error (future) 438: "3.6ref.c", line 35 # The initializer for a non-constant reference must be an lvalue. Try ** changing 'const int *&' to 'const int *const &' at ["3.6ref.c", line 35]. **             const int *&pi_ref = &ival; **                                  ^^^^^  ** error C2440: “初始化”: 无法从“const int *”转换为“const int *&”// VS2010 **/// ok: 这是可以被编译器接受的// const int *const &pi_ref = &ival;//ival的值和其地址都是常量// cout << "ival=" << ival << ", *pi_ref=" << *pi_ref << endl;/** ** const int ival = 1024;/int ival = 1024; ** => &ival 是 const int *类型的一个rvalue,  ** => 只能邦定到一个和它的类型相匹配的const引用上 **/typedef const int* T;const int ival = 1024;// T& pi_ref = &ival;// error: rvalue不能邦定到非const引用上const T& pi_ref = &ival;// ok: 保存&ival的临时变量, 邦定到const引用上cout << "ival=" << ival << ", *pi_ref=" << *pi_ref << endl;return 0;}