不同的参数传递方式(P41)

/*

在C++中,函数调用时参数的传递有两种方式:传值和传引用

传值:传递对象的值  void SwapValue(int a,int b)

传引用:传递对象的首地址值  void SwapValue(int &a,int &b)

*/

#include<iostream>
using namespace std;

void SwapValue(int a,int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
cout<<"在SwapVaule()函数中:\t\ta="<<a<<",b="<<b<<endl;
return ;
};

void SwapRef(int &a,int &b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
cout<<"在SwapRef()函数中:\t\ta="<<a<<",b="<<b<<endl;
return ;
};

int main()
{
int a=10,b=20;
cout<<"数据交换前:\t\ta="<<a<<",b="<<endl;
SwapValue(a,b);
cout<<"调用SwapVal()后:\t\ta="<<a<<",b="<<b<<endl<<endl;
a = 10;
b = 20;
SwapRef(a,b);
cout<<"调用SwapRef()后:\t\ta="<<a<<",b="<<b<<endl<<endl;
return 0;
}

posted @ 2020-02-23 18:53  CollisionDimension  阅读(203)  评论(0)    收藏  举报