七.引用(从C到C++)

内容参考于《21天学通C++》(第八版)

七.引用(从C到C++)

1. 示例1
#include <iostream>
using namespace std;
int main()
{
	int original = 30;
	cout << "original = " << original << endl;
	cout << "original is at address: " << hex << &original << endl;

	int& ref1 = original;
	cout << "ref1 is at address: " << hex << &ref1 << endl;

	int& ref2 = ref1;
	cout << "ref2 is at address: " << hex << &ref2 << endl;
	cout << "Therefore, ref2 = " << dec << ref2 << endl;

	return 0;
}

运行结果

original = 30
original is at address: 006FF9C0
ref1 is at address: 006FF9C0
ref2 is at address: 006FF9C0
Therefore, ref2 = 30
2. 作用

引用是变量的别名。声明引用时,需要将其初始化为一个变量,因此引用只是另一种访问相应变量存储的数据的方式。输出表明,无论将引用初始化为变量(如第 9 行所示)还是其他引用(如第 12 行所示),它都指向相应变量所在的内存单元。 因此, 引用是真正的别名, 即相应变量的另一个名字。 第 14 行显示了 ref2的值,结果与第 6 行显示的original 值相同,因为 ref2 是 original 的别名,它们位于内存的同一个地方。

3. 示例2
#include <iostream>
using namespace std;

const double Pi = 3.1416;
// output parameter result by reference
void Area(double radius, double& result)
{
	result = Pi * radius * radius;
}

int main()
{
	cout << "Enter radius: ";
	double radius = 0;
	cin >> radius;

	double areaFetched = 0;
	Area(radius, areaFetched);

	cout << "The area is: " << areaFetched << endl;
	return 0;
}

这份代码正确输出了areaFetched的值。很明显这是个C中最大的区别,double& result,以引用传递参数。使用return语句时,函数只能返回一个值。因此,如果函数需要执行影响众多值的操作,且需要在调用者中使用这些值,则按引用传递参数是让函数将修改结果提供给调用模块的方式之一。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值