什么叫引用
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
int original = 30;
cout << "address of original: " << hex << &original << endl;
// 定义一个ref引用original
int& ref = original;
cout << "address of ref: " << hex << &ref << endl;
cout << dec << ref << endl;
return 0;
}
address of original: 0x7ffc14a1acfc
address of ref: 0x7ffc14a1acfc
30
可以看到original
和ref
的地址和数值都是一样的,所以引用就相当于起了个别名,注意与指针区别
引用有什么用
函数在传参数的时候,如果是按值传递,将会对变量进行复制,如果变量很大,就会消耗很多的时间和内存,所以使用引用可以对变量本身直接继续修改
#include <iostream>
using namespace std;
void DoSomeThing(int& val) {
cout << "address of val: " << hex << &val << endl;
val += 100; // 对变量值进行增加操作
}
int main(int argc, char const *argv[])
{
int original = 30;
cout << "address of original: " << hex << &original << endl;
int& ref = original;
cout << "address of ref: " << hex << &ref << endl;
cout << dec << ref << endl;
DoSomeThing(ref);
cout << dec << original << endl;
return 0;
}
address of original: 0x7ffc14a1acfc
address of ref: 0x7ffc14a1acfc
30
address of val: 0x7ffc14a1acfc
130
可以看到最初的变量
original
的值发生了变化,按引用传递的形参的地址还是和原来一样的
const引用
有时候我们希望函数只能使用传递的参数,不能修改他,就需要加个const
const int& ref2 = ref;
int num = 10;
ref2 = num; // 报错,ref2是只读参数,不能作为左值
ref2 = 100; // 报错,ref2是只读参数,不能作为左值
void DoSomeThing(const int& val) {
cout << "address of val: " << hex << &val << endl;
val += 100; // 报错,ref2是只读参数,不能作为左值
}
不能修改的加个const
,需要修改的就不用加const
,可以像下面这样写
void DoSomeThing(const int& val, int& res) {
res = val * val;
}
int main(int argc, char const *argv[])
{
int original = 30;
int res = 0;
DoSomeThing(original, res);
cout << original << endl;
cout << res << endl;
return 0;
}
30 //const引用的值没有被改变
900 //没有const的值被修改了