int main(){ int x { 5 }; // x is a normal integer variable int& ref { x }; // ref is an lvalue reference variable that can now be used as an alias for variable x std::cout << x << '\n'; // print the value of x (5) std::cout << ref << '\n'; // print the value of x via ref (5) return 0;}
在上面的例子中,使用 int& 定义ref 可以创建一个对int类型左值的引用,然后我们使用一个左值表达式 x 对其进行了初始化。从此以后,我们就可以将 ref 作为 x 的同义词来使用。程序会打印如下内容:
#include <iostream>int main(){ int x { 5 }; // normal integer variable int& ref { x }; // ref is now an alias for variable x std::cout << x << ref; // print 55 x = 6; // x now has value 6 std::cout << x << ref; // prints 66 ref = 7; // the object being referenced (x) now has value 7 std::cout << x << ref; // prints 77 return 0;}
打印结果:
556677
在上面的例子中,ref 是 x 的别名,所以我们可以通过 x 或者 ref 来修改 x 的值。
左值引用的初始化
和常量非常类似,所有的引用都必须被初始化。
int main(){ int& invalidRef; // error: references must be initialized int x { 5 }; int& ref { x }; // okay: reference to int is bound to int variable return 0;}
int main(){ int x { 5 }; int& ref { x }; // valid: lvalue reference bound to a modifiable lvalue const int y { 5 }; int& invalidRef { y }; // invalid: can't bind to a non-modifiable lvalue int& invalidRef2 { 0 }; // invalid: can't bind to an r-value return 0;}
int main(){ int x { 5 }; int& ref { x }; // okay: reference to int is bound to int variable double y { 6.0 }; int& invalidRef { y }; // invalid; reference to int cannot bind to double variable double& invalidRef2 { x }; // invalid: reference to double cannot bind to int variable return 0;}
对void类型的左值引用是不可以的(这么做的目的又是什么呢?)
引用不能被重新设置(使其引用其他对象)
引用一旦被初始化,它便不能够被重新绑定到其他对象。
新手 C++ 程序员经常会尝试使用赋值运算符重新设置引用。这么做是可以编译并运行的,但是它的效果并不是我们期望的那样,考虑下面的代码:
#include <iostream>int main(){ int x { 5 }; int y { 6 }; int& ref { x }; // ref is now an alias for x ref = y; // assigns 6 (the value of y) to x (the object being referenced by ref) // The above line does NOT change ref into a reference to variable y! std::cout << x; // user is expecting this to print 5 return 0;}
结果可能出人意料:
6
当表达式中的引用进行求值时,它会解析成被引用的对象。所以 ref = y 并不会为 ref 重新设置为y的引用。实际情况是ref是x的引用,因此上面的表达式等价于x = y ,因为 y 的值为 6 ,所以 x 被赋值为 6 。
#include <iostream>int main(){ int x { 5 }; { int& ref { x }; // ref is a reference to x std::cout << ref; // prints value of ref (5) } // ref is destroyed here -- x is unaware of this std::cout << x; // prints value of x (5) return 0;} // x destroyed here