1. 引用
1.1 引用的概念和定义
引用不是新定义一个变量,而是给已存在变量取了一个别名,编译器不会为引用变量开辟内存空间(指针会开辟空间),它和它引用的变量共用同一块内存空间。比如:水浒传中林冲,外号豹子头
类型&引用别名=引用对象;
C++ 中为了避免引入太多的运算符,会复用 C 语言的一些符号,比如前面的<<和>>,这里引用也和取地址使用了同一个符号&。
如何区分取地址和引用呢?
&i->在变量之前是取地址
int&->在类型之后是引用
#include <iostream>
using namespace std;
int main() {
int a = 0;
// 引用:b 和 c 是 a 的别名
int& b = a;
int& c = a;
// 也可以给别名 b 取别名,d 相当于还是 a 的别名
int& d = b;
// 这里取地址我们看到是一样的
cout << &a << endl;
cout << &b << endl;
cout << &c << endl;
cout << &d << endl;
return 0;
}

#include <iostream>
using namespace std;
int main() {
int a = 0;
int& b = a;
int& c = a;
int& d = b;
++d; // ++d 就相当于 ++b,也就是 ++a
cout << &a << endl; // 这里的&是取地址
cout << &b << endl;
cout << &c << endl;
cout << &d << endl;
;
}





