一、问题引入
在C++的中新增一个特性:按引用传递变量,虽然与按传递变量的地址可以实现相同的结果,但引用有其独特的地方。
引用传递: 引用经常被用作函数参数,使得函数中的变量名成为调用程序中的变量的别名。
通过引用变量用作参数,函数将使用原始数据,而不是其副本。
二、解决过程
举例说明:
#include <iostream>
using namespace std;
void swapv(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 swapq(int & a, int & b) // 传引用变量
{
int temp = a;
a = b;
b = temp;
}
int main(void)
{
int wallet1 = 120;
int wallet2 = 50;
cout << "source wallet1:" << wallet1 << endl;
cout << "source wallet2:" << wallet2 << endl;
cout << endl;
swapv(wallet1, wallet2);
cout << "传变量的值" << endl;
cout << "wallet1:" << wallet1 << endl;
cout << "wallet2:" << wallet2 << endl;
cout << endl;
wallet1 = 120;
wallet2 = 50;
swapp(&wallet1, &wallet2);
cout << "传变量的地址" << endl;
cout << "wallet1:" << wallet1 << endl;
cout << "wallet2:" << wallet2 << endl;
cout << endl;
wallet1 = 120;
wallet2 = 50;
swapq(wallet1, wallet2);
cout << "传变量" << endl;
cout << "wallet1:" << wallet1 << endl;
cout << "wallet2:" << wallet2 << endl;
cout << endl;
return 0;
}
标签:变量,temp,int,C++,传递,函数参数,引用
From: https://www.cnblogs.com/caojun97/p/17317803.html