引用的基本yu'fa
作用:给变量起别名
语法:数据类型&别名=原名
#include<iostream>
using namespace std;
int main()
{
int a = 10;
int &b = a;
b = 20;
cout << b << endl;
cout << a << endl;
return 0;
}
a和b两个变量操作的是同一块内存空间。
引用的注意事项
- 引用必须初始化
引用在初始化后,不可以改变
#include<iostream> using namespace std; int main() { int a = 10; int &b = a; b = 20;//这里是修改变量的指而不是改变b的指向。 //int &c;引用必须初始化 cout << b << endl; cout << a << endl; return 0; }
引用做函数参数
作用:函数传参时,可以利用引用的技术让形参修饰实参
优点:可以简化指针修改实参
#include<iostream>
using namespace std;
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main()
{
int a = 10, b = 20;
swap(a, b);
cout << a << endl;
cout << b << endl;
return 0;
}
引用做函数返回值
作用:引用是可以作为函数的返回值存在的
注意:不要返回局部变量引用
用法:函数调用作为左值
#include<iostream>
using namespace std;
int& test() {
static int a = 10;
return a;
}
int main()
{
int &ref = test();
cout << ref << endl;
test() = 1000;//函数可以作为左值
cout << ref << endl;
return 0;
}
引用的本质
本质:引用的本质在c++内部实现是个指针常量
#include<iostream>
using namespace std;
int main()
{
int a = 10;
int& ref = a;//int * const ref=&a;
ref=20;//*ref=20;
cout << a << endl;
cout << ref << endl;
return 0;
}
结论:C++推荐用引用技术,因为语法方便,引用本质是指针常量,但是所有的指针操作编译器都帮我们做了
常量引用
作用:常量引用主要用来修饰形参,防止误操作
在函数形参列表中,可以加const修饰形参,,防止形参改变实参
#include<iostream>
using namespace std;
void showValue(const int& ref) {
//ref = 20; 不可以修改
cout << ref;
}
int main()
{
int a = 10;
//int& ref = 10;引用必须引用一块合法的内存空间
//加上const,编译器会给我们做一些优化,int temp=10;const int &ref =temp;
//const int& ref = 10;
//ref = 20;加入const之后变为只读,不可以修改。
showValue(a);
return 0;
}