#include <iostream>


  

using namespace std;


  

struct Teacher
{
char name[64];
int age;


  

};


  

//在被调用函数 获取资源
int getTeacher(Teacher **p)
{
if (p == NULL)
{
return - 1;
}
Teacher *tmp = NULL;
tmp = (Teacher*)malloc(sizeof(Teacher));
if (tmp == NULL)
{
return -2;
}
tmp->age = 20;
*p = tmp;
}


  

int getTeacher1(Teacher*& p)
{
//给p赋值,相当于给main函数中的pt赋值
p = (Teacher*)malloc(sizeof(Teacher));
if (p == NULL)
{
return -1;
}
p->age = 30;
}


  

void FreeTeacher(Teacher* tmp)
{
if (tmp == NULL)
{
return;
}
free(tmp);
}


  

void main()
{
Teacher *pt = NULL;
//C语言中的二级指针
getTeacher(&pt);
cout << "age:" << pt->age << endl;
FreeTeacher(pt);


  

//C++中的引用(指针引用)
getTeacher1(pt);//引用的本质 间接赋值后2个条件 让C++编译器帮我们做了
cout << "age:" << pt->age << endl;
FreeTeacher(pt);
system("pause");
}

 

 

 

 1     //引用:一个指针常量(常指针)
 2     //常引用:是让变量引用只读属性,y不能修改x
 3     int x = 20;
 4     const int &y = x;
 5 
 6     const int a = 10;//C++编译器把a放在符号表中
 7     const int& m = 11;//C++编译器会分配内存空间
 8 
 9     1)常引用const int &e相当于 const int* const e
10     2)普通引用 int &e 相当于 int* const e

 

转载于:https://www.cnblogs.com/Yu-Weijie/p/11434230.html

Logo

GitCode AI社区是一款由 GitCode 团队打造的智能助手,AI大模型社区、提供国内外头部大模型及数据集服务。

更多推荐