1、基本使用
作用:给变量起别名
语法:数据类型 &别名 = 原名
int a = 10;
int& b = a;
b = 20;
//a的值为20
cout << "a = " << a << endl;
2、引用的注意事项
注意:引用必须声明时直接初始化,引用一旦初始化后就不能更改值了
int a = 10;
int& b = a;
引用在初始化后,不可以改变
int c = 20;
cout << a << "\t" << b << "\t" << c << "\t" << endl;
输出结果:10 10 20
b = c;
//赋值操作,而不是更改引用
cout << a << "\t" << b << "\t" << c << "\t" << endl;
输出结果:20 20 20
b = 11;
cout << a << "\t" << b << "\t" << c << "\t" << endl;
输出结果:11 11 20
3、引用做函数参数
作用:函数传参时,可以利用引用的技术让形参修饰实参
优点:可以简化指针修改实参
//交换函数:
1)值传递
void MySwap01(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << "MySwap01值传递" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
2)地址传递
void MySwap02(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
cout << "MySwap02 地址传递" << endl;
cout << "a = " << *a << endl;
cout << "b = " << *b << endl;
}
3)引用传递
void MySwap03(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
cout << "MySwap03 引用传递" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
函数实现调用:
int a = 10;
int b = 20;
MySwap01(a, b);
cout << endl;
cout << "Main 值传递" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << endl;*/
//地址传递:形参会修饰实参
/*int c = 10;
int d = 20;
MySwap02(&c, &d);
cout << endl;
cout << "Main 地址传递" << endl;
cout << "c = " << c << endl;
cout << "d = " << d << endl;
cout << endl;*/
//引用传递:形参会修饰实参
/*int e = 10;
int f = 20;
MySwap03(e, f);
cout << endl;
cout << "Main 地址传递" << endl;
cout << "e = " << e << endl;
cout << "f = " << f << endl;
4、引用做函数返回值
作用:引用是可以作为函数的返回值存在的
注意:不要返回局部变量引用
引用做函数返回值:
//1、不要返回局部变量引用
int& test1()
{
int a = 10;//局部变量存放在四区的 栈区
return a;
}
//2、函数调用可以作为左值
int& test2() {
static int a = 10;//静态变量
return a;
}
int& ref = test1();
第一次结果正确,是因为编译器做了保留
cout << "ref = " << ref << endl;
第二次结果错误,因为a的内存已经释放
cout << "ref = " << ref << endl;
输出结果:第二个ref值已经乱码
ref = 10
ref = 258067424
用法:函数调用可以作为左值
int& ref2 = test2();
cout << "ref2 = " << ref2 << endl;
//输出结果:无论输出多少次都没有问题
ref2 = 10
test2() = 1000;//如果函数的返回值是引用,这个函数调用可以作为左值
cout << "ref2 = " << ref2 << endl;
//输出结果:无论输出多少次都没有问题
ref2 = 1000
5、引用的本质
本质:引用的本质在C++内部实现是一个指针常量
PS:发现是引用,转换为int* const ref = &a;
void func(int& ref)
{
ref = 100;
}
int a = 10;
自动转换为 int* const ref = &a;
指针常量的指针指向不可改,也说明为什么引用不可更改
int& ref = a;
ref = 20;//内部发现ref是引用,自动帮我们转换为:*ref = 20;
//cout << "a = " << a << endl;
//cout << "ref = " << ref << endl;
//func(a);
6、常量引用
使用场景:用来修饰形参,防止误操作
//常量引用(打印数据函数)
void showValue(const int &val)
{
//此时无法再对参数val进行值修改
cout << "val = " << val << endl;
}
int a = 10;
//语法错误:引用必须引一块合法的内存空间
int& ref = 10;
//加上const之后 编译器将代码修改为
int temp = 10; const int& ref = temp;
const int& ref = 10;
//报错信息:表达式必须是可修改的左值
ref = 20;//加入const之后变为只读,不可以修改
//函数利用常量引用防止误操作修改实参
int a = 10;
showValue(a);