引用类型
引用就是变量的别名
//基本类型
int x = 1;
int& p = x;
p = 2;
printf("%d\n", x);
//类
class MyClass
{
public:
int x;
};
MyClass p;
MyClass& px = p;
px.x = 10;
printf("%d\n", p.x);
//指针
int* p = (int*)1;
int*& a = p;
a = (int*)2;
printf("%d\n", p);
//数组
int arr[] = {1, 2, 3};
int (&p)[3] = arr;
p[0] = 4;
printf("%d\n", arr[0]);
引用的本质
引用的本质就是指针
引用和指针的区别
- 引用必须初始化,而且只能指向一个变量。
- 对引用赋值,是对其指向的变量进行赋值,而不是修改引用本身的值。
- 对引用做运算,是对其指向的变量做运算,而不是对引用本身做运算。
- 引用类型就是一个"弱化了的指针"。
引用在函数参数传递中的作用(基本类型)
#include <iostream>
void Plus(int& i)
{
i++;
return;
}
int main()
{
int i = 10;
Plus(i);
printf("%d\n", i);
return 0;
}
引用在函数参数传递中的作用(构造类型)
#include <iostream>
struct Base
{
int x;
int y;
Base(int x, int y)
{
this->x = x;
this->y = y;
}
};
void PrintByRef(Base& refb, Base* pb)
{
//通过指针读取
printf("%d %d\n", pb->x, pb->y);
//通过引用读取
printf("%d %d\n", refb.x, refb.y);
//可以重新赋值、做运算吗?
//refb = (Base&)1;
//refb++;
return;
}
常引用
- 引用是为了避免对指针进行错误的操作。
- 常引用是为了对一个对象进行只读操作,它指向的内容也不希望被修改。
#include <iostream>
class Base
{
public:
int x;
};
void PrintA(Base& ref)
{
//ref = 100; //不能修改
//ref.x = 200 //可以修改引用指向的内容
printf("%d\n", ref.x);
return;
}
//常引用
void PrintB(const Base& ref)
{
//ref = 100; //不能修改
//ref.x = 200 //不能修改引用指向的内容
printf("%d\n", ref.x);
return;
}
int main()
{
Base b;
b.x = 100;
PrintA(b);
return 0;
}
总结
引用解决了指针能被读取/修改,导致的程序崩溃或出错。