1.C++中引用可以在一定程度上代替二级指针的作用,比如下面代码中的getTeacher2()函数中,形参使用用指针的引用,代替了二级指针。
2.还可以用定义常引用的方式,实现用字面量给引用赋值,字面量没有内存空间,所以在初始化时C++编译器会偷偷地给引用分配内存空间,但是字面量还是没有内存空间。
#include "iostream"
using namespace std;
struct Teacher
{
char name[64];
int age;
};
int getTeacher(Teacher **p)
{
Teacher *tmp = NULL;
if (p == NULL)
{
return -1;
}
tmp = (Teacher *)malloc(sizeof(Teacher));
if (tmp == NULL)
{
return -2;
}
tmp->age = 33;
*p = tmp;
}
int getTeacher2(Teacher * &p)
{
p = (Teacher *)malloc(sizeof(Teacher));
if (p == NULL)
{
return -1;
}
p->age = 66;
}
void freeTeacher(Teacher *p)
{
if (p == NULL)
{
return ;
}
free(p);
}
int main01()
{
Teacher *pt1 = NULL;
//1 c语言中的二级指针
getTeacher(&pt1);
cout << "pt1->age = " << pt1->age << endl;
freeTeacher(pt1);
//2 c++中的引用
getTeacher2(pt1);
cout << "pt1->age = " << pt1->age << endl;
freeTeacher(pt1);
system("pause");
return 0;
}
void printfTeacher(const Teacher &tmp) //常引用做函数形参,只能用,不能改
{
cout <<"tmp.age = "<< tmp.age << endl;
}
void main()
{
//int &a = 10; //这种赋值是错误的,字面量10没有内存空间,无法起别名
const int &a = 10; // 可以通过常引用的方式,实现字面量给引用赋值
cout << a << endl;
Teacher t2;
t2.age = 77;
printfTeacher(t2);
system("pause");
}