- 引用的注意事项
// 引用注意事项, 不能返回局部变量的引用
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;
}
- 指针的使用
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这个指针变量的 地址传递进去,所以就用到了二级指针.
- 重点来了,指针的引用,如下代码:
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;
}
- 引用的本质
{// 引用的本质
int a = 3;
int &p = a; // 其本质就是 int* const p = &a;
p = 5; // 其本质就是 *p = 5;
}
来源:CSDN
作者:weixin_43903378
链接:https://blog.csdn.net/weixin_43903378/article/details/103791911