- 指针的引用
- 利用引用可以简化指针
- 可以直接用同级指针的 引用 给同级指针分配空间
- 常量的引用
- const int &ref = 10;
- // 加了const之后, 相当于写成 int temp = 10; const int &ref = temp;
- 常量引用的使用场景 修饰函数中的形参,防止误操作
指针引用
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
struct Person
{
int age;
};
void allocateSpace(Person ** p)
{
//p指向指针的指针,二级指针 *p 指针 指向的是person 本体 **p person本体
*p = (Person *)malloc(sizeof(Person));
(*p)->age = 10;
}
void test01()
{
Person * p = NULL;
allocateSpace(&p);
cout << "p.age = " << p->age << endl;
}
void allocateSpace2(Person* &pp) // Person * &pp = p;
{
pp = (Person *)malloc(sizeof(Person));
pp->age = 20;
}
void test02()
{
Person *p = NULL;
allocateSpace2(p);
cout << "p.age = " << p->age << endl;
}
int main(){
//test01();
test02();
system("pause");
return EXIT_SUCCESS;
}
常量引用
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
void test01()
{
//int &ref = 10;
const int &ref = 10; // 加了const之后, 相当于写成 int temp = 10; const int &ref = temp;
int *p = (int *)&ref;
*p = 10000;
cout << ref << endl;
}
void showValue(const int &a)
{
//a = 100000;
cout << "a = " << a << endl;
}
//常量引用的使用场景 修饰函数中的形参,防止误操作
void test02()
{
int a = 100;
showValue(a);
}
int main(){
//test01();
test02();
system("pause");
return EXIT_SUCCESS;
}