引用的本质在C++内部实现是一个指针常量
C++编译器在编译过程中使用常指针作为引用的内部实现,因此引用所占用的空间大小与指针相同,只是这个过程是编译器内部实现,用户不可见。
#include<iostream>
using namespace std;
// 发现是引用,转换为int *const ref=&a;
void testFunc(int &ref) {
ref = 100;
}
int main() {
int a = 10;
int &aRef = a; // 自动转换为int *const aRef=&a;这也能说明引用为什么必须初始化
aRef = 50; // 内部发现aRef是引用,自动帮我们转换为:*aRef=20;
cout << "a:" << a << endl;
cout << "aRef:" << aRef << endl;
testFunc(a);
system("pause");
return EXIT_SUCCESS;
}