c++的传值与引用

来源:互联网 发布:sql字段前加内容 db2 编辑:程序博客网 时间:2024/05/16 12:16

这两天了解到c++的引用,今天就来两个例子:

#include<iostream>#include<cstdlib>using namespace std;typedef struct student{int num;struct student *next;}stu;void init(stu* &s)//当这里的参数s是引用时,是完全正确的;但是若去掉&直接传值,编译时便会报错使用了未初始化的局部变量“s”。{s=(stu*)malloc(sizeof(stu));s->next=NULL;}int main(void){stu* s;init(s);system("pause");return 0;}

#include<iostream>#include<cstdlib>using namespace std;typedef struct student{int num;struct student *next;}stu;void init(stu* &s){s=(stu*)malloc(sizeof(stu));s->next=NULL;}void push(stu* &s)//引用与不引用{stu* p;p=s;for(int i=0;i<4;i++){s=(stu*)malloc(sizeof(stu));s->num=i;p->next=s;p=s;}}void show(stu* s){printf("%d\n",s->num);//引用时//printf("%d\n",s->next->num);//不引用时}int main(void){stu* s;init(s);push(s);show(s);system("pause");return 0;}


1 0
原创粉丝点击