引用就是给变量起别名 两者地位相同
数据类型 &别名=原名

[] [c++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<bits/stdc++.h>
using namespace std;

int main()
{
int a=10;
int &b=a;//引用必须初始化 一旦初始化后不能发生改变
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
b=100;
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
}

请看注释 引用做参数更方便

[] [c++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<bits/stdc++.h>
using namespace std;

//值传递
void swap01(int a,int b)
{
int t=b;
b=a;
a=t;
}
//地址传递
void swap02(int *a,int *b) //传入的是地址 所以需要用指针接收
{
int t=*a;
*a=*b;
*b=t;
}

//引用传递
void swap03(int &a,int &b) //&a和&b是a,b的别名 形参会修饰实参
{
int t=a;
a=b;
b=t;
}

int main()
{
int a=10;
int b=20;

swap01(a,b);
cout<<a<<" "<<b<<endl;

swap02(&a,&b);
cout<<a<<" "<<b<<endl;

a=10;
b=20;
swap03(a,b);
cout<<a<<" "<<b<<endl;

}

引用作函数的返回值
1.不要返回局部变量的引用 因为局部变量存放在栈区 函数结束会被释放
2.函数的调用可以作为左值

[] [c++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<bits/stdc++.h>
using namespace std;

int& test01()
{
static int a=10;
return a;
}
int main()
{
int &ref=test01();
cout<<"ref="<<ref<<endl;

//如果函数返回值是引用 可以作为左值
test01()=1000;
cout<<"ref="<<ref<<endl; //这个时候ref已经是a的别名 修改a等于修改ref
return 0;
}

引用的本质其实是一个指针常量 一旦初始化后就不能改变指向

[] [c++]
1
2
3
4
5
6
7
8
9
10
11
12
13
void func(int &ref)
{
ref=100; //ref是引用 转换为*ref=100;
}

int main()
{
int a=10;
//自动转换为int* const ref=&a
int& ref=a;
//发现ref是引用 转换为*ref=20
ref=20;
}

常量引用 用来修饰形参 防止误操作
const int &ref=10
修饰后变为只读 不能修改