C++基础 引用
目录
1.引用的基本使用
2.引用的注意事项
3.引用做函数参数
4.引用做函数返回值
5.引用的本质
1.引用的基本使用
作用:给变量起别名
语法:数据类型 &别名 = 原名
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int &b = a; //创建引用
b = 20;
cout << a << endl;
}
结果:
通过输出结果可以看出通过操作别名b,也能改变变量a的值
2.引用的注意事项
1.引用必需要初始化
int &b; (×)
int &b=a; (√)
2.引用一旦初始化,就不可以更改了
解释:比如c是a的别名,就不能再是b的别名了
3.引用做函数参数
作用:函数传参时,可以利用引用让形参修饰实参
优点:可以简化指针修改实参
比较值传递、地址传递、引用传递:
值传递:
#include <iostream>
using namespace std;
#include <string>
//值传递
void swap01(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << " a= " << a << endl;
cout << " b= " << b << endl;
}
int main()
{
int a = 10;
int b = 20;
swap01(a, b);
cout << " a= " << a << endl;
cout << " b= " << b << endl;
}
结果:
可以发现值传递中,形参不会修饰实参
地址传递:
#include <iostream>
using namespace std;
#include <string>
//地址传递
void swap02(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
cout << " a= " << *a << endl;
cout << " b= " << *b << endl;
}
int main()
{
int a = 10;
int b = 20;
swap02(&a, &b);
cout << " a= " << a << endl;
cout << " b= " << b << endl;
}
结果:
可以发现地址传递中形参会修饰实参
引用传递:
#include <iostream>
using namespace std;
#include <string>
//引用传递,形参会修饰实参
void swap03(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
cout << " a= " << a << endl;
cout << " b= " << b << endl;
}
int main()
{
int a = 10;
int b = 20;
swap03(a, b);
cout << " a= " << a << endl;
cout << " b= " << b << endl;
}
结果:
可以发现引用传递中形参会修饰实参
4.引用做函数返回值
4.1. 不要返回局部变量引用
#include <iostream>
using namespace std;
int& test01()
{
int a = 10;
return a;
}
int main()
{
int &ref = test01();
cout << " ref= " << ref << endl;
cout << " ref= " << ref << endl;
}
结果:
结果不一样是因为a是局部变量,其存放在栈区,当函数test01执行完毕后就被释放了。
4.2函数的调用可以作为左值从而来被赋值
#include <iostream>
using namespace std;
#include <string>
int& test02()
{
static int a = 10;
return a;
}
int main()
{
int &ref = test02();
cout << " ref= " << ref << endl;
cout << " ref= " << ref << endl;
test02() = 1000;
cout << " ref= " << ref << endl;
cout << " ref= " << ref << endl;
}
结果:
前两个结果一样是因为a是静态变量,其存放在全局区,程序结束后由系统释放。
后来ref的值变为1000是由于 原名a被重新赋了值1000,ref作为一个别名引用的内存的值也发生了变化。
5.引用的本质
引用的本质在C++内部实现是一个指针常量
引用一旦初始化后就不可以发生改变
#include <iostream>
using namespace std;
#include <string>
void func(int& ref)
{
ref = 100;
}
int main()
{
int a = 10;
int& ref = a; //相当于转换为 int* const ref=&a;
ref = 20; //内部发现ref是引用,自动帮我们转换为 *ref=20;
cout << " a= " << a << endl;
cout << " ref= " << ref << endl;
func(a);
}