(C++)将引用用作函数参数——讲解+程序例子

引用经常被用作函数参数,使得函数中的变量名成为调用程序中的变量的别名,通俗易懂的讲,就是将形参变成实参的别名。这种传递参数的方法称为按引用传递

C语言只能按值传递,按值传递导致被调用函数使用程序的值的拷贝,因此C语言采用按指针传递的方式,避开按值传递的限制;而按引用传递允许被调用的函数能够访问调用函数中的变量。

下面举个简单的例子:
交换两个变量的值,比较一下使用引用和指针,还有按值传递参数的方法作为参考。

程序例子:

#include <iostream>

using namespace std;

void swap1(int & a, int & b);
void swap2(int *pa , int *pb);
void swap3(int a , int b);

int main(void)
{
	int apple1 = 100;
	int apple2 = 200;
	cout << "apple1 = " << apple1 << endl;
	cout << "apple2 = " << apple2 << endl;
	
	//使用引用作为参数,按引用交换
	cout << "Using references to swap contents: " << endl;
	swap1(apple1,apple2);
	cout << "apple1 = " << apple1 << endl;
	cout << "apple2 = " << apple2 << endl;
	
	//使用指针作为参数,按指针交换
	cout << "Using pointers to swap contents: " << endl;
	swap2(&apple1,&apple2);
	cout << "apple1 = " << apple1 << endl;
	cout << "apple2 = " << apple2 << endl;
	
	//使用按值传递作为参数,按值交换
	cout << "Using values to swap contents: " << endl;
	swap3(apple1,apple2);
	cout << "apple1 = " << apple1 << endl;
	cout << "apple2 = " << apple2 << endl;
		
	return 0;
}

void swap1(int & a , int & b)
{
	int temp;
	
	temp = a;
	a = b;
	b = temp;
}

void swap2(int *pa , int *pb)
{
	int temp;
	
	temp = *pa;
	*pa = *pb;
	*pb = temp;
}

void swap3(int a , int b)
{
	int temp;
	
	temp = a;
	a = b;
	b = temp;
}

运行结果:

apple1 = 100
apple2 = 200
Using references to swap contents:
apple1 = 200
apple2 = 100
Using pointers to swap contents:
apple1 = 100
apple2 = 200
Using values to swap contents:
apple1 = 100
apple2 = 200

--------------------------------
Process exited after 0.3331 seconds with return value 0
请按任意键继续. . .

其中交换函数必须能够修改调用程序中的变量的值。这就意味着按值传递变量是不管用的,因为函数讲交换原始变量的副本的内容,而不是变量本身的内容。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小黄TimTim仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值