引用
- 作用:起别名
引用的本质在c++内部实现是一个指针常量
注意事项:
引用必须引一块合法内存空间
不能返回局部变量的引用
void test1001() {
int a = 10;
int& b = a;
b = 100;
cout << a << endl;//输出100
cout << b << endl;//输出100
}
void test1002() {
int a = 10;
//引用必须初始化
int &b = a;
//引用一旦初始化就不可以引向其他变量
int c = 20;
b = c;
cout << a << endl;//输出20
cout << b << endl;//输出20
cout << c << endl;//输出20
}
- 对数组建立引用
void test1003() {
//直接建立引用
int arr[10];
int(&pArr)[10] = arr;
for (int i = 0; i < 10; i++)
{
arr[i] = 100 + i;
}
for (int i = 0; i < 10; i++)
{
cout << pArr[i] << endl;
}
cout << "=============" << endl;
//先定义数组类型,再通过类型定义引用
typedef int(ARRAY_TYPE)[10];
ARRAY_TYPE& pArr2 = arr;
for (int i = 0; i < 10; i++)
{
cout << pArr2[i] << endl;
}
}
参数传递
//值传递:外部无效
void mySwap01(int a, int b) {
int temp = a;
a = b;
b = temp;
}
//地址传递:外部有效
void mySwap02(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
//引用传递:外部有效
void mySwap03(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
void test1101() {
int a = 10;
int b = 20;
//mySwap01(a, b);
//mySwap02(&a, &b);
mySwap03(a, b);
cout << a << " " << b << endl;
}
指针的引用
利用引用可以简化指针
可以直接用同级指针的引用给同级指针分配空间
void allocateSpace2(Person* &p) {
p = (Person*)malloc(sizeof(Person));
p->age = 20;
}
void test1202() {
Person* p = NULL;
allocateSpace2(p);
cout << "p.age=" << p->age << endl;
}
常量的引用
void test1301() {
const int& ref = 10;
int* p = (int*)&ref;
*p = 100;
cout << ref;//输出100,常量引用可以通过指针修改
}
常量引用的使用场景:修饰函数中的形参,防止误操作
void showValue(const int& a) {
a = 1000;//a不能直接做左值,编译不通过
cout <<"inner_a=" << a << endl;
}