double i = 42.0; double &r = i; std::cout << "the value of i is " << i << std::endl; std::cout << "the value of r is " << r << std::endl; std::cout << "the address of i is "<< &i << std::endl; std::cout << "the address of r is " << &r << std::endl;
定义一个double类型的变量,并对其进行同类型引用,输出如下:
1 2 3 4
the value of i is 42 the value of r is 42 the address of i is 0x7ffcf8119c88 the address of r is 0x7ffcf8119c88
可以看到,不仅指向的字面值相等,其内存地址也相等。
非const引用的限制
非const引用只能进行同类型引用,否则编译器会报错 比如:
1 2
double i = 42.0; int &r = i;
运行程序,会报错:
1 2 3 4
In function ‘intmain()’: error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’ int &r = i; ^
double i = 42.0; constint &r = i; std::cout << "the value of i is " << i << std::endl; std::cout << "the value of r is " << r << std::endl; std::cout << "the address of i is "<< &i << std::endl; std::cout << "the address of r is " << &r << std::endl;
最终会输出不同的内存地址:
1 2 3 4
the value of i is 42 the value of r is 42 the address of i is 0x7ffc1a38a528 the address of r is 0x7ffc1a38a524
也就是说,其实在引用时进行了如下操作:
1 2 3
double i = 42.0; int temp = i; constint &r = temp;
double i = 42.0; constdouble &r = i; i = 50.0; std::cout << "the value of i is " << i << std::endl; std::cout << "the value of r is " << r << std::endl; std::cout << "the address of i is "<< &i << std::endl; std::cout << "the address of r is " << &r << std::endl;
输出结果如下:
1 2 3 4
the value of i is 50 the value of r is 50 the address of i is 0x7fff7d83b988 the address of r is 0x7fff7d83b988