对引用参数&的理解

来源:互联网 发布:阿里云服务器托管 编辑:程序博客网 时间:2024/05/29 17:24
#include<stdio.h>#include<malloc.h>struct node{    int s;    struct node *l;    struct node *r;};int sum=0;int n;void creat (struct node *&a,int key)    //改成struct node *a不对{    if(a==NULL)    {        a=(struct node *)malloc(sizeof(struct node));        a->s=key;        a->l=NULL;        a->r=NULL;    }    else    {        if(key>=a->s)   //改成>不对        {            creat(a->l,key);        }        else if(key<a->s)        {            creat(a->r,key);        }    }}void zx(){    if(a==NULL)    {        return ;    }    zx(a->l);    sum++;    if(sum!=n)    printf("%d ",a->s);    else printf("%d\n",a->s);    zx(a->r);}int main(){    while(~scanf("%d",&n))    {        sum=0;        struct node *b;        b=NULL;        int i;        for(i=1;i<=n;i++)        {            int k;            scanf("%d",&k);            creat(b,k);        }        zx(b);    }}#include<stdio.h>int a;int main(){    int &p=a;    a=2;    printf("%d\n",p);}

在c++中,&有两种含义,其中一种是取地址,另一种就是引用。 

引用是C++中的概念,初学者容易把引用和指针混淆一起。

一下程序中,n是m的一个引用(reference),m是被引用物(referent)。

int m;

int &n = m;

n相当于m的别名(绰号),对n的任何操作就是对m的操作。

所以n既不是m的拷贝,也不是指向m的指针,其实n就是m它自己。


在上面的程序的主函数中,b我并没有分配内存,而是让他为一个空指针,如果creat的参数我用struct node *a,这时a和b虽然都是NULL,但是都没有具体的指向地址,当在creat函数中给a分配内存时(即a有了新的地址指向),虽然之前a,b都是NULL,但此时的b的指向并没有更改,而用struct node *&a就不一样了,这里的a就是b的一个别名,creat函数中为a分配了内存也就是为b分配了内存。也就是当用struct node *时a和b是两个指针,用struct node *& 时,a和b是同一个指针。struct node *就像是两个人重名而struct node *就像是一个人大名和小名。

当事先为b分配好内存(即b指向一个具体的地址而不是NULL)时,struct node*和struct node *&对程序的影响几乎一样(但意义不同),否则struct node *和struct node *&是不一样的,以上程序就是后者。



0 0
原创粉丝点击