给变量起别名
数据类型 &别名 = 原名
#include
using namespace std;
int main(){
int a = 10;
int& b = a;
cout << b << endl;
system("pause");
return 0;
}
注意:
要初始化
。初始化后就不可以更改
。#include
using namespace std;
int main(){
int a = 10;
int& b = a;
int c = 20;
//初始化后不能更改
int &b = c; //错误 因为已经初始化过了
cout << c << endl;
system("pause");
return 0;
}
函数传参时,可以利用引用让形参修饰实参。可以简化指针修改实参。
#include
using namespace std;
//值传递
void swap01(int a,int b) {
int temp = a;
a = b;
b = temp;
}
//地址传递
void swap02(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
//引用传递
void swap03(int& a, int& b) { //等于就是起别名修改
int temp = a;
a = b;
b = temp;
}
int main(){
int a = 10;
int b = 20;
system("pause");
return 0;
}
不要返回局部变量的引用
函数的调用可以作为左值
#include
using namespace std;
//不要返回局部变量引用
//int& test01() {
// int a = 10;//局部变量存放在四区中的栈区
// return a;
//}
int& test02() {
static int a = 10;
return a;
}
int main(){
int& ref2 = test02();
test02() = 1000;
//如果返回值是引用,这个函数调用可以作为左值。
cout << "ref2: " << ref2 << endl;
cout << "ref2: " << ref2 << endl;
cout << "ref2: " << ref2 << endl;
system("pause");
return 0;
}