进一步说明引用、指针在函数传递中的运用。(记住这三种交换方式)
来源:互联网 发布:邮箱验证正则表达式 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;
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
- 进一步说明引用、指针在函数传递中的运用。(记住这三种交换方式)
- c++中函数参数传递(值传递、指针传递,引用传递)进一步认识
- c++中函数参数传递(值传递、指针传递,引用传递)进一步认识
- c++中函数参数传递(值传递、指针传递,引用传递)进一步认识
- 引用和指针在交换中的区别
- 函数返回值的传递方式(值传递、指针传递、引用传递)
- 指针在函数中的传递
- 【转载】C++中引用传递与指针传递区别(进一步整理)
- C++中引用传递与指针传递区别(进一步整理)
- C++中引用传递与指针传递区别(进一步整理)
- C++中引用传递与指针传递区别(进一步整理)
- C++中引用传递与指针传递区别(进一步整理)
- C++中引用传递与指针传递区别(进一步整理)
- C++中引用传递与指针传递区别(进一步整理)
- C++中引用传递与指针传递区别(进一步整理)
- [转载]C++中引用传递与指针传递区别(进一步整理)
- C++函数参数和返回值三种传递方式:值传递、指针传递和引用传递(着重理解)
- C++函数参数和返回值三种传递方式:值传递、指针传递和引用传递(着重理解)
- C\C++ windows 绕过strptime
- OpenGl 坐标转换
- ubuntu 14.04 python mysql 安装
- nginx 多服务配置
- 如何在linux系统之间共享文件
- 进一步说明引用、指针在函数传递中的运用。(记住这三种交换方式)
- POJ 2485 Highways
- Hibernate进阶
- Apache 管理 Tomcat集群配置
- C++中关于拷贝构造函数
- iOS 使用ContactsUI保存新联系人到系统通讯录
- Javaweb环境部署总结
- 在web工程中使用Spring依赖注入
- 第五讲 二维费用的背包问题 HD FATE(二维完全背包)