引用的本质是对变量起别名。
&是取地址符,在局部变量中,数据存在栈区,可以通过引用访问同一块内存。
#include <iostream>using namespace std;int main() {int a = 10;int& b = a;cout << "a = " << a << endl << "b = " << b << endl;b = 20;cout << "a = " << a << endl << "b = " << b << endl;return 0;}
引用必须初始化,且初始化后不可更改。
引用可简化一些内存操作。
#include <iostream>using namespace std;void swap1(int* a, int* b) {int t;t = *a;*a = *b;*b = t;}void swap2(int& a, int& b) {int t;t = a;a = b;b = t;}int main() {int a = 10;int b = 20;swap1(&a, &b);swap2(a, b);return 0;}
//返回局部变量引用int& test01() {int a = 10; //局部变量return a;}//返回静态变量引用int& test02() {static int a = 20;return a;}int main() {//不能返回局部变量的引用int& ref = test01();cout << "ref = " << ref << endl;cout << "ref = " << ref << endl;//如果函数做左值,那么必须返回引用int& ref2 = test02();cout << "ref2 = " << ref2 << endl;cout << "ref2 = " << ref2 << endl;test02() = 1000;cout << "ref2 = " << ref2 << endl;cout << "ref2 = " << ref2 << endl;system("pause");return 0;}
引用的本质在c++内部实现是一个指针常量.
讲解示例:
//发现是引用,转换为 int* const ref = &a;void func(int& ref){ref = 100; // ref是引用,转换为*ref = 100}int main(){int a = 10;//自动转换为 int* const ref = &a; 指针常量是指针指向不可改,也说明为什么引用不可更改int& ref = a;ref = 20; //内部发现ref是引用,自动帮我们转换为: *ref = 20;cout << "a:" << a << endl;cout << "ref:" << ref << endl;func(a);return 0;}
结论:C++推荐用引用技术,因为语法方便,引用本质是指针常量,但是所有的指针操作编译器都帮我们做了
C++支持运算符重载,我们可以自己创建操作方法。
