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

来源:互联网 发布:邮箱验证正则表达式 js 编辑:程序博客网 时间:2024/06/08 17:54
#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的值,但另外两个就不一样了。这才是本文要注意的。所以变换值得用指针或者引用。

0 0
原创粉丝点击