函数参数的3种传递方式

来源:互联网 发布:linux命令全集app 编辑:程序博客网 时间:2024/06/15 23:23

按值传递:

 #include<iostream.h>
void swap(int,int);
void main()
{
int a=10,b=20;
cout<<"a="<<a<<",b="<<b<<endl;
swap(a,b);
cout<<"swapped:"<<endl;
cout<<"a="<<a<<",b="<<b<<endl;
}
void swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
 引用传递:

类型 &引用名=已有的变量;

#include<iostream.h>
void swap(int&,int&);
void main()
{
int a=10,b=20;
cout<<"a="<<a<<",b="<<b<<endl;
swap(a,b);
cout<<"swapped:"<<endl;
cout<<"a="<<a<<",b="<<b<<endl;
}
void swap(int &x,int &y)
{
int temp;
temp=x;
x=y;
y=temp;
}

地址传递:

#include<iostream.h>
void swap(int*,int*);
void main()
{
int a=10,b=20;
cout<<"a="<<a<<",b="<<b<<endl;
swap(&a,&b);
cout<<"swapped:"<<endl;
cout<<"a="<<a<<",b="<<b<<endl;
}
void swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}