在c++中引用常被用做函数的参数,使得函数中的变量名成为调用程序中的变量的别名。这种传递参数的方法叫做引用传递。按引用传递允许被调用函数访问调用函数中的变量,对比C语言中的按值传递,按值传递导致被调用函数使用调用程序的值的拷贝。同时在c语言中也可以避免按值传递,就是使用按指针传递的方式进行传递。

#include <iostream>

using namespace std;

void swapr(int& a, int& b);
void swapp(int* a, int* b);
void swapv(int a, int b);

int main()
{
	int wallet1 = 300;
	int wallet2 = 350;
	cout << "wallet1 = " << wallet1 << endl;
	cout << "wallet2 = " << wallet2 << endl;
	cout << endl;


	cout << "using reference swap" << endl;
	swapr(wallet1, wallet2);
	cout << "wallet1 = " << wallet1 << endl;
	cout << "wallet2 = " << wallet2 << endl;
	cout << endl;

	cout << "using pointer swap" << endl;
	swapp(&wallet1, &wallet2);
	cout << "wallet1 = " << wallet1 << endl;
	cout << "wallet2 = " << wallet2 << endl;
	cout << endl;

	cout << "using pass value swap" << endl;
	swapv(wallet1, wallet2);
	cout << "wallet1 = " << wallet1 << endl;
	cout << "wallet2 = " << wallet2 << endl;
	cout << endl;
	return 0;
}
void swapr(int& a, int& b)
{
	int temp = a;
	a = b;
	b = temp;
}
void swapp(int* a, int* b)
{
	int temp = *a;
	*a = *b;
	*b = temp;
}
void swapv(int a, int b)
{
	int temp = a;
	a = b;
	b = temp;
}

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部