进一步说明引用、指针在函数传递中的运用。(记住这三种交换方式)

#include<iostream>
void swapr(int &a, int&b);
void swapp(int *p1, int*p2);
void swapv(int a, int b);
int main()
{
using namespace std;
int apple = 300;
int pear = 350;
cout << "apple =" << apple << endl;
cout << "pear =" << pear << endl;


cout << "User swapr change :" << endl;
swapr(apple, pear);
cout << "apple =" << apple << endl;
cout << "pear =" << pear << endl;


cout << "User swapp change :" << endl;
swapp(&apple, &pear);
cout << "apple =" << apple << endl;
cout << "pear =" << pear << endl;


cout << "User swapv change :" << endl;
swapv(apple, pear);
cout << "apple =" << apple << endl;
cout << "pear =" << pear << endl;
return 0;
}
void swapr(int&a, int&b)
{
int temp = 0;
temp = a;
a = b;
b = temp;
}
void swapp(int*p1, int*p2)
{
int temp = 0;
temp = *p1;
*p1 = *p2;
*p2 = temp;
}


void swapv(int a, int b)
{
int temp = 0;
temp = a;
a = b;
b = temp;

}



结果不同是因为,在swapv中变量a和b 只是复制了apply和pear的值,而swapr和swapp中的a和b是apple和pear的别名,所以swapv中只是变换了a和b的值,不影响apple和pear的值,但另外两个就不一样了。这才是本文要注意的。所以变换值得用指针或者引用。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值