#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;
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的值,但另外两个就不一样了。这才是本文要注意的。所以变换值得用指针或者引用。