在c++中引用常被用做函数的参数,使得函数中的变量名成为调用程序中的变量的别名。这种传递参数的方法叫做引用传递。按引用传递允许被调用函数访问调用函数中的变量,对比C语言中的按值传递,按值传递导致被调用函数使用调用程序的值的拷贝。同时在c语言中也可以避免按值传递,就是使用按指针传递的方式进行传递。
#include <iostream>
using namespace std;
void swapr(int& a, int& b);
void swapp(int* a, int* b);
void swapv(int a, int b);
int main()
{
int wallet1 = 300;
int wallet2 = 350;
cout << "wallet1 = " << wallet1 << endl;
cout << "wallet2 = " << wallet2 << endl;
cout << endl;
cout << "using reference swap" << endl;
swapr(wallet1, wallet2);
cout << "wallet1 = " << wallet1 << endl;
cout << "wallet2 = " << wallet2 << endl;
cout << endl;
cout << "using pointer swap" << endl;
swapp(&wallet1, &wallet2);
cout << "wallet1 = " << wallet1 << endl;
cout << "wallet2 = " << wallet2 << endl;
cout << endl;
cout << "using pass value swap" << endl;
swapv(wallet1, wallet2);
cout << "wallet1 = " << wallet1 << endl;
cout << "wallet2 = " << wallet2 << endl;
cout << endl;
return 0;
}
void swapr(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 swapv(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » C++引用和函数参数
发表评论 取消回复