引用的注意事项

1.引用必须初始化
2.引用初始化后不可改变

int a=0;
int c=10;
//当b成为a的别名后,无法再成为变量c的别名
int &b=a;
b=c;//赋值操作

3.

#include<iostream>
using namespace std;
void test()
{
    
    
	int a = 10;
	int& b = a;
	int& c = b;
	int& d = c;
	cout << d << endl;
}
int main()
{
    
    
	system("pause");
	return 0;
}

在这里插入图片描述
4.
注意:编译器保留返回的局部变量地址只会为调用函数的下一行代码保留一次

#include<iostream>
using namespace std;
int& test()
{
    
    
	int a = 10;
	return a;
}
int main()
{
    
    
	//用引用接收返回值为局部变量的引用时,变量a已经被释放,别名n是变量a的别名,因此n已经被释放
	//第一次访问编译器会进行一次保留,后面就会变为随机值,因为内存的操作权限还给了操作系统
	int& n = test();
	cout << n << endl;
	cout << n << endl;
	cout << n << endl;
	cout << test() << endl;
	cout << test() << endl;
	cout << test() << endl;
	system("pause");
	return 0;
}

在这里插入图片描述
在这里插入图片描述
5.函数调用可以作为左值

#include<iostream>
using namespace std;
int& test()
{
    
    
	//静态变量,存放在全局区
	//全局区上的数据在程序结束后由系统释放
	static int a = 10;
	return a;
}
int main()
{
    
    
	int& n = test();
	cout << n << endl;
	cout << n << endl;
	//因为返回的是引用,即是静态变量a本身,因此可以对a的值进行修改操作
	test() = 520;
	cout << n << endl;
	cout << test() << endl;
	system("pause");
	return 0;
}

在这里插入图片描述
6.引用的本质
本质:引用在c++内部实现是一个指针常量
在这里插入图片描述
7.常量引用

  1. 常量引用可以做常量的别名
  2. 常量引用如果做其他类型变量的别名,那么变量值无法修改
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_53157173/article/details/113924501
今日推荐