引用的基本使用
作用:给变量起别名
语法:数据类型 &别名 = 原名;
#include <iostream>
using namespace std;
int main()
{
int a = 20;
int& b = a;
cout << "a = " << a << endl;
cout<<"b= " << b << endl;
b = 100;
cout << "a = " << a << endl;
cout << "b= " << b << endl;
system("pause");
return 0;
}
引用注意事项
- 引用必须初始化
- 引用在初始化后,不可以改变
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int &b = a;
int c = 20;
cout << "a =" << a << endl;
cout << "b =" << b << endl;
b = c; //赋值操作,不是更改引用
cout << "a =" << a << endl;
cout << "b =" << b << endl;
cout << "c =" << c << endl;
system("pause");
return 0;
}
引用做函数参数
作用:函数传参时,可以利用引用的技术让形参修饰实参
优点:可以简化指针修改实参
#include <iostream>
using namespace std;
//值传递
void test1(int a,int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
//地址传递
void test2(int* a, int* b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
//引用传递
void test3(int &a,int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
int main()
{
int a = 10;
int b = 20;
test1(a, b);//值传递,形参不会修饰实参,不能更改main函数a、b的值
cout << "test1 a=" << a << endl;
cout << "test1 b=" << b << endl;
test2(&a, &b);//地址传递,形参会修饰实参,会更改main函数a、b的值
cout << "test2 a=" << a << endl;
cout << "test2 b=" << b << endl;
//经过上面的地址传递,a、b已经互换了数值。
test3(a, b);//引用传递,形参会修饰实参,不用取地址符&,且会更改main函数a、b的值
cout << "test3 a=" << a << endl;
cout << "test3 b=" << b << endl;
system("pause");
return 0;
}
总结:通过引用参数产生的效果同地址传递是一样的。引用的的语法更清楚简单。
引用做函数返回值
作用:引用是可以作为函数的返回值存在的
注意:不要返回局部变量引用
用法:函数调用作为左值
#include <iostream>
using namespace std;
//不要返回局部变量的引用
int& test1()
{
int a = 10; //局部变量存放在四区中的栈区,在函数执行完自动释放
return a;
}
int& test2()
{
static int a = 10; //静态变量存放在全局区,在程序结束时由操作系统释放
return a;
}
int main()
{
int& ref = test1();
cout << "test ref=" << ref << endl;//第一次结果正确,是因为编译器做了保留
cout << "test ref=" << ref << endl;//第二次结果错误,是因为a的内存已经释放
int& ref1 = test2();
cout << "test ref1=" << ref1 << endl;
cout << "test ref1=" << ref1 << endl;
//函数的调用可以作为左值
test2() = 1000;
cout << "test ref1=" << ref1 << endl;
cout << "test ref1=" << ref1 << endl;
system("pause");
return 0;
}
引用的本质
本质:引用的本质在c++内部实现是一个指针常量
int a = 10;
int &ref = a;//自动转换为 int * const ref = &a; 指针常量是指针指向不可改,也说明为什么引用不可更改
ref = 20; //内部发现ref是引用,自动帮我们转换为*ref = 20;
结论:c++推荐引用技术,因为语法方便,引用本质是指针常量,但是所有的指针操作编辑器都帮我们做了。
常量引用
作用:常量引用主要用来修饰形参,防止误操作
在函数形参列表中,可以加const修饰形参,防止形参改变实参
#include <iostream>
using namespace std;
void test1(int &ref)
{
ref = 1000;
cout << "test1 ref=" << ref << endl;
}
//函数中利用常量引用防止误操作修改实参
void test2(const int& ref)
{
//ref = 1000;//会报错
cout << "test2 ref=" << ref << endl;
}
int main()
{
//int& ref = 10;//错误写法,引用本身需要一个合法内存
//加入const就可以了,编辑器优化代码,int temp =10;const int& ref = temp;
const int& ref = 10;
int a = 10;
test1(a);
a = 10;
test2(a);
system("pause");
return 0;
}