大约耗时1分钟
引用如何使用
语法 : 数据类型 &别名 = 原名
int main(){int a = 10;int &b = a;cout << "a = " << a << endl;cout << "b = " << b <<endl;b = 6666;cout <<"a = " << a << endl;cout << "b = " << b << endl;}输出结果:a = 10b = 10a = 6666b = 6666
引用的注意点
int main(){int &b;//报错 未初始化 error: 'b' declared as reference but not initializedint a = 10;int &c = a;//正确int d = 20;c = d; //这个是赋值操作 不是更改引用return 0;}
引用作为函数形参
#include<iostream>#include<string.h>using namespace std;//值传递void swap01(int a, int b){int temp = a;a = b;b = temp;}//地址传递void swap02(int *a, int *b){int temp = *a;*a = *b;*b = temp;}//引用传递 这里 a 和 b 就是实参的别名void swap03(int &a, int &b){int temp = a;a = b;b = temp;}int main(){int a = 10;int b = 20;swap03(a, b);cout << "a = " << a << endl;cout << "b = " << b << endl;return 0;}输出结果:a = 20b = 10
值传递,只是形参的值会替换,实际值不会变
地址传递,都会改变
引用传递,都会改变
引用作为函数返回值
#include<iostream>#include<string.h>using namespace std;//返回局部变量引用int& test01(){//局部变量存在栈区int a = 10;return a;}//返回静态变量引用int& test02(){//静态变量存在全局区static int a = 20;return a;}int main(){int &ref = test02();cout << "ref = " << ref << endl;test02() = 66666; // test02 返回的变量static int a 和 ref 是接收 test02返回的别名 操作结果是一样的cout << "after ref = " << ref << endl;return 0;}输出结果:warning: reference to local variable 'a' returned [-Wreturn-local-addr]int a = 10;^ref = 20after ref = 66666
出现的waring 是因为test01方法返回了栈区的变量引用,这个在方法调用完就会被释放的,程序检查出来了。如果你要运行这个方法,那么要么报错,要么卡死在这
引用的本质
void func(int& ref){ref = 100; //等价于 *ref = 100;}int main(){int a = 10;//自动转换为 int* const ref = &a;指针常量 指向不可修改,即引用不能修改int& ref = a;ref = 20; // 内部发现是引用,会自动转换成 *ref = 20cout << "a : " << a << endl;cout << "ref :" << ref <<endl;func(a);return 0;}
int & ref = a 等价于 int const ref = &a 常量指针
*所以引用本质其实就是一个指针常量
常量引用
常量引用最重要的作用就是来修饰形参,防止函数体内修改到实参
#include<iostream>
#include<string.h>
using namespace std;
void showValue(const int & v){
v+=100;//注意这里 修改了常量引用的值
cout << "showValue v = " << v << endl;
}
int main(){
int a = 10;
int& ref = a;
cout << "ref = " << ref << endl;
showValue(ref);
cout << "after showValue ref = " << ref << endl;
}
执行报错
error: assignment of read-only reference 'v'
v+=100;
常量引用的作用相信你已经ok了。但是你还有可能会问,我引用为什么要这样写 int& ref = a ,为什么不能直接int& ref = 10,首先我们引用是给变量起别名,你是变量么?这么写,而且引用本身需要一个合法的内存空间,毕竟引用就是一个常量指针,我指向的内存地址肯定要是合法的。
但是 const int & ref = 10 写法是对的。加了const 编译器会将代码修改为如下 int temp =10, const int& ref = temp,但依旧是不能修改的。
