C++:引用类型(int &)
引用类型
给变量起别名
数据类型 &别名 = 原名
#include <iostream>
using namespace std;
int main(){
int a = 10;
int& b = a;
cout << b << endl;
system("pause");
return 0;
}
🎈注意:
- 引用
要初始化
。 - 引用
初始化后就不可以更改
。
与&p取地址不同,不要混淆。
#include <iostream>
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 <iostream>
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 <iostream>
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;
}
posted on 2022-04-16 09:47 Michael_chemic 阅读(211) 评论(0) 编辑 收藏 举报