C++ 对引用的理解4

笑着哭i 提交于 2020-01-18 03:41:32
  1. 引用的注意事项
// 引用注意事项, 不能返回局部变量的引用
int & test3() { //因为局部变量出了函数体外 就会被销毁
	int a = 10;
	return a;
}

// 引用注意事项, 返回值如果是引用, 那么函数可以作为左值进行运算
int & test4() {
	static int a = 100;
	return a;
}
int main()
{	
	test4() = 300;
	cout << test4() << endl;   // 输出300
	return 0;
}

  1. 指针的使用
struct Person {
	int age;
	int id;
	string name;
};

void allocSpace(Person **p) {   // Person **p = &per;
	*p = (Person *)malloc(sizeof(Person));  // *p 就是 per这个 指针变量, 指向了(就是存储了对象的堆内存地址) Person结构体对象内存
	(*p)->age = 10;
	(*p)->id = 1;
}
int main()
{	
	Person *per = NULL;    // 这时候 per 是一个指针变量(可以指向Person结构体的指针变量)
	allocSpace(&per);      // 对这个 per 指针变量取地址运算&, allocSpace函数形参是为 Person数据类型的 二级指针
	cout << per->age << endl;
	cout << per->id << endl;
	free(per);
	return 0;
}
// 这里考虑为什么函数参数用二级指针, 这和交换变量的内容时的原理是一样的。
// int a=3;b=5; 用函数交换ab的值,需要传递ab的地址,同理这里Person *per = NULL; 如果让per能关联到allocSpace分配的堆内存,也需要将per这个指针变量的 地址传递进去,所以就用到了二级指针.
  1. 重点来了,指针的引用,如下代码:
struct Person {
	int age;
	int id;
	string name;
};
void allocSpace2(Person* &p) { // Person* &p = per; 本质上为 Person** const p = &per;
	p = (Person *)malloc(sizeof(Person)); // p本身存放的实际内容其实是per这个指针变量所在的内存地址, 因为p是引用类型所以编译给我们优化了
	p->age = 23;
	p->id = 2;
}

void test6() {
	Person *per = NULL;
	allocSpace2(per);
	cout << per->age << endl;
	cout << per->id << endl;
	free(per);
}
int main()
{	
	test6();
	return 0;
}
  1. 引用的本质
{// 引用的本质
	int a = 3;
	int &p = a;   //  其本质就是  int* const p = &a;
	p = 5;        //  其本质就是  *p = 5;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!