在C语言中,使用指针(Pointer)可以间接获取、修改某个变量的值

int age = 20;
int *rAge = &age;
cout << *rAge << endl;
*rAge = 30;
cout << age << endl;  // 30

在C++中,使用引用(Reference)可以起到跟指针类似的功能

注意点:引用相当于变量别名(基本数据类型,枚举,结构体,类,指针,数组等,都可以有引用)

1.定义一个引用,相当于是变量的别名

int age = 20;
int &rAge = age;
rAge = 40;
cout << age << endl;
// 40

2.枚举

enum Season {
	Spring, // 默认为0开始
	Summer, // 1
	Fall,// 2
	Winter // 3
};

Season season;
Season &rSeason = season;
rSeason = Winter;
cout << season << endl; // 输出3

3.结构体

struct Student{
	int age;
};

Student stu;
Student &rStu = stu;
rStu.age = 20;
cout << stu.age << endl;  // 输出20

4.指针

int a = 10;
int b = 20;

int *p = &a;
int *&rP = p;

rP = &b;
*p = 30;

cout << a << endl;
cout << b << endl;

5.数组

int array[] = { 3,4,5 };
int (&rArray)[3] = array;

cout << rArray[2] << endl;
// 取出第2+1个值 == 5

6.函数返回值可以被赋值

// 全局变量
int age = 10;

int &func() {
	/* 相当于这样写
	int &rAge = age;
	return rAge;
	*/
	return age;
}

func() = 40;
cout << func() << endl;

7.交互值

void swap(int &a, int &b) {
	int temp = a;
	a = b;
	b = temp;
}

int v1 = 11;
int v2 = 22;
swap(v1, v2);

cout << v1 << endl; // 22
cout << v2 << endl; // 11

###v引用存在的价值之一:比指针更安全、函数返回值可以被赋值

注意点