一、前言
引用是变量别名,简化指针语法,用于函数传参、返回值,无需手动操作地址,可读性远高于指针。本篇详解普通引用、const 常量引用,对比指针差异。
二、引用基础语法
数据类型 &别名 = 原变量;
引用必须在定义时初始化,且终身绑定同一个变量,无法更改绑定对象。
cpp
运行
int a = 100;
int &b = a; // b是a的别名,共用同一块内存
cout << a << endl;
cout << b << endl;
b = 666;
cout << a << endl; // a同步变为666
修改引用,原始变量同步变化,二者完全等价。
三、引用做函数参数(引用传递,替代指针)
无需传地址,直接传递变量,函数内修改同步影响外部实参,代码简洁。
交换数字简化版
cpp
运行
#include <iostream>
using namespace std;
void swapData(int &x, int &y)
{
int temp = x;
x = y;
y = temp;
}
int main()
{
int m = 5, n = 8;
swapData(m, n);
cout << m << " " << n; // 8 5
return 0;
}
对比指针版本,省去&传地址、*解引用,降低语法复杂度。
四、const 常量引用
普通引用允许修改原变量,常量引用仅可读、不可修改,适合传递大型数据(数组 / 字符串)避免拷贝。
cpp
运行
string text = "C++常量引用";
const string &s = text;
// s = "test"; 编译报错,常量引用禁止修改数据
函数只读参数推荐使用 const 引用:
cpp
运行
void showStr(const string &str)
{
cout << str;
}
五、引用做函数返回值
可返回局部变量引用(谨慎使用)、全局 / 静态变量引用,支持链式调用。
cpp
运行
int arr[5] = {1,2,3,4,5};
int &getVal(int index)
{
return arr[index];
}
int main()
{
getVal(0) = 99; // 通过返回引用修改数组元素
cout << arr[0]; // 输出99
return 0;
}
六、指针与引用核心区别对照表
表格
七、新手避坑
引用定义未初始化:
int &b;直接编译报错函数返回局部变量引用:局部变量函数结束销毁,引用悬空,访问乱码
混淆
&引用定义和&取地址运算符
八、综合实战:引用批量修改学生分数
cpp
运行
#include <iostream>
using namespace std;
void addScore(int &s, int add)
{
s += add;
}
int main()
{
int score1 = 70, score2 = 82;
addScore(score1, 10);
addScore(score2, 5);
cout << score1 << " " << score2; // 80 87
return 0;
}
九、下期预告
下一篇:C++ 结构体 struct 自定义复合数据类型实战