C/C++引用(Reference)

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 示例

  • 源代码:

在这里插入图片描述

  • 运行结果:

在这里插入图片描述

  • 分析:

传参使用“引用”或“指针”类型时,可以执行交换功能,而普通的“变量”类型则不行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值