关于涵数调用的若干思考

来源:互联网 发布:朝鲜留学 知乎 编辑:程序博客网 时间:2024/05/01 04:45


首先让我们看一下下面几个小程序:
(输入两个数,按大小顺序输——观察一下输出的数值是否能达到目的)
//值传递
#include<iostream>
using namespace std;
int main()
{
 void max(int a,int b);
 int x,y;
        cin>>x>>y;
 max(x,y);
 cout<<x<<endl<<y<<endl;
return 0;
}
void max(int a,int b)
{
 int temp;
    if(a<b)
 {
 temp=a;
 a=b;
 b=temp;
 }
}


//指针传递
#include<iostream>
using namespace std;
int main()
{
 void max(int*p1,int*p2);
 int x,y;
 int *point_1,*point_2;
        cin>>x>>y;
 point_1=&x;
 point_2=&y;
 max(point_1,point_2);
 cout<<x<<endl<<y<<endl;
return 0;
}
void max(int*p1,int*p2)
{
 int temp;
    if(*p1<*p2)
 {
 temp=*p1;
 *p1=*p2;
 *p2=temp;
 }
}

 

//数组传递
#include<iostream>
using namespace std;
int main()
{
 void max(int a[]);
 int a[2];
        cin>>a[0]>>a[1];
 max(a);
 cout<<a[0]<<endl<<a[1]<<endl;
return 0;
}
void max(int a[])
{
 int temp;
    if(a[0]<a[1])
 {
 temp=a[0];
 a[0]=a[1];
 a[1]=temp;
 }
}

//引用传递
#include<iostream>
using namespace std;
int main()
{
 void max(int &,int &);
 int x,y;
        cin>>x>>y;
 max(x,y);
 cout<<x<<endl<<y<<endl;
return 0;
}
void max(int &a,int &b)
{
 int temp;
    if(a<b)
 {
 temp=a;
 a=b;
 b=temp;
 }
}

读者不难发现,第一个涵数是达不到预期目的的,其它三个都可以。聪明的同学一看也就明白,第一个涵数实参传递的是值(相当于把实参的值赋给形参。其它的都可以看作是传址(指针自然不必说,数组传的是首地址,引用就是地址的复制)对同一地址内数据的操作。

原创粉丝点击