1.1引用的基本使用
作用: 给变量起别名
语法: 数据类型 &别名 = 原名
#include<iostream>
using namespace std;
int main() {
int a = 1;
int &b = a;
cout << a << " ";
cout << b << " ";
b = 2;
cout <<"新输出的数据:"<< a << " ";
cout << b <<endl;
system("pause");
return 0;
}
输出:1 1 新输出的数据:2 2 请按任意键继续. . . 注意:
int a = 1;
int b = 2;
int &c = a;
int &c = b;
c = b;
1.2 引用做函数参数
作用: 函数传参时,可以利用引用的技术让形参修饰实参
优点: 可以简化指针修改实参
void change_01(int a, int b) {
a = 3;
b = 4;
}
int main() {
int a = 1;
int b = 2;
cout << "a = " << a << " b = " << b << endl;
change_01(a, b);
cout << "a = " << a << " b = " << b << endl;
system("pause");
return 0;
}
输出:
a = 1 b = 2
a = 1 b = 2
请按任意键继续. . .
void change_02(int* a, int* b) {
* a = 3;
* b = 4;
}
change_02(&a, &b);
a = 1 b = 2
a = 3 b = 4
请按任意键继续. . .
void change_03(int& a, int& b) {
a = 3;
b = 4;
}
change_03(a, b);
a = 1 b = 2
a = 3 b = 4
请按任意键继续. . .
总结:通过引用参数产生的效果同按地址传递是一样的。
1.3 引用函数做返回值
#include<iostream>
using namespace std;
int& h_1() {
static int a = 10;
return a;
}
int& h_2() {
static int a = 20;
return a;
}
int main() {
int& b_1 = h_1();
cout << "b_1 = " << b_1 << endl;
cout << "b_1 = " << b_1 << endl;
int& b_2 = h_2();
cout << "b_2 = " << b_2 << endl;
cout << "b_2 = " << b_2 << endl;
h_2() = 1000;
cout << "b_2 = " << b_2 << endl;
cout << "b_2 = " << b_2 << endl;
system("pause");
return 0;
}
结论:
int& ref = a;
ref = 20;
1.4 常量引用
作用: 常量引用主要用来修饰形参,防止误操作
- 在函数形参列表中,可以加
const 修饰形参,防止形参改变实参
void print_a(const int& b) {
b += 10;
cout << b << endl;
}
int a = 10;
print_a(a);
错误: [Error] assignment of read-only reference 'b'
const int& c = 10;
cout << c << endl;
|