1 定义
-
引用就是另一个变量的别名(A reference is an alias for another variable)。
-
通过引用所做的读写操作实际上是作用于原变量上(Any changes made through the reference variable are actually performed on the original variable)。
2 声明
- 声明引用类型的变量:
int val;
int& rval = val;
或者
int val, &rval = val;
- 注:(编程规范)
51.C++指针与引用符号应靠近其类型而非名字(C++ pointers and references should have their reference symbol next to the type rather than to the name)。
比如:
int* val; //NO int *val;
int& ref; //NO int &ref;
3 函数传参
- 函数参数:引用传递(Function parameters:pass by reference)
引用可做函数参数,但调用时只需传普通变量即可(You can use a reference variable as a parameter in a function and pass a regular variable to invoke the function)。
在被调用函数中改变引用变量的值,则改变的是实参的值(When you change the value through the reference variable, the original value is actually changed)。
4 示例
- 源代码:
- 运行结果:
- 分析:
传参使用“引用”或“指针”类型时,可以执行交换功能,而普通的“变量”类型则不行。