通过引用使多个变量名对应同一内存空间,可以作为函数的参数和返回值使用,其本质为指针常量。
一、引用的规则和本质
引用必须初始化,初始化后指向不可更改。
//由此可知引用的本质是指针常量,指针常量的指向不可改。因此引用初始化后不可更改
int main()
{
int a = 1;
int b = 3;
//必须要初始化,且不能初始化为常量
//int& ref;
//int& ref = 1;
//char& ref = 'a';
//发现引用符号,int& ref = a自动转换为int* const ref = &a
int& ref = a;
cout << " a为" << a << endl;
cout << " ref为" << ref << endl << endl;
//发现ref是引用,自动转换为: *ref = 20
ref = 2;
cout << " a为" << a << endl;
cout << " ref为" << ref << endl << endl;
//只能将a和ref的值改为b的值,无法使ref不再指向a而重新指向b
ref = b;
cout << " a为" << a << endl;
cout << " ref为" << ref << endl;
cout << " b为" << b << endl << endl;
ref = 4;
cout << " a为" << a << endl;
cout << " ref为" << ref << endl;
cout << " b为" << b << endl << endl;
return 0;
}
二、引用的使用
1.作为函数参数
在函数传参时采用引用的方式,让形参也对应实参所对应的内存空间。这即可以实现在函数内对实参进行修改,相比于指针的方式更加简洁方便。
//指针传递
void Swap1(int* p, int* q)
{
int temp = *p;
*p = *q;
*q = temp;
}
//引用传递
void Swap2(int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
int main()
{
//用指针操作内存空间地址实现交换功能
int a = 1;
int b = 2;
cout << " a为" << a << endl;
cout << " b为" << b << endl << endl;
Swap1(&a, &b);
cout << " a为" << a << endl;
cout << " b为" << b << endl << endl;
//用引用使内存空间对应多个变量名实现交换功能
int c = 3;
int d = 4;
cout << " c为" << c << endl;
cout << " d为" << d << endl << endl;
Swap2(c, d);
cout << " c为" << c << endl;
cout << " d为" << d << endl << endl;
return 0;
}
2.作为函数返回值
当引用作为函数返回值时,不能返回局部变量的引用。
int g_a = 10;
static int g_s_b = 20;
//返回局部变量的引用
int& test1()
{
int a = 1;
return a;
}
//返回静态局部变量的引用
int& test2()
{
static int s_a = 2;
return s_a;
}
//返回全局变量的引用
int& test3()
{
return g_a;
}
//返回静态全局变量的引用
int& test4()
{
return g_s_b;
}
int main()
{
//局部变量的引用无法返回,是因为函数test1()执行完毕后返回的是一个变量名 a
// a 对应的内存空间 M 已经释放, a 不再有任何指向
//当用新的引用名ref1指向 a 时,虽然表面上不会报错
//但实际上ref1已经无法实现指向功能,在后续程序中也无法发挥任何作用
//除局部变量外的引用均可返回
int& ref1 = test1();
cout << " ref1 = " << ref1 << endl;
int& ref2 = test2();
cout << " ref2 = " << ref2 << endl;
int& ref3 = test3();
cout << " ref3 = " << ref3 << endl;
int& ref4 = test4();
cout << " ref4 = " << ref4 << endl << endl;
//如果函数做左值,那么必须返回引用
test1() = 100;
test2() = 200;
test3() = 1000;
test4() = 2000;
cout << " ref1 = " << ref1 << endl;
cout << " ref2 = " << ref2 << endl;
cout << " ref3 = " << ref3 << endl;
cout << " ref4 = " << ref4 << endl << endl;
//ref1已经无法实现指向功能,在后续程序中也无法发挥任何作用
ref1 = 10000;
cout << " ref1 = " << ref1 << endl;
int* z = &ref1;
*z = 100000;
cout << " ref1 = " << ref1 << endl;
return 0;
}
三、常量引用
通过关键字const的修饰,引用也可以对某一内存空间进行首次命名,即初始化为常量。
int main()
{
//引用本身需要一个合法的内存空间,因此报错
//int& ref = 10;
//加入const即可,编译器内设置临时内存空间temp对代码自动优化
//int temp = 10; const int& ref = temp;
const int& ref = 10;
cout << ref << endl;
//加入const后不可以修改变量
//ref = 100;
cout << ref << endl;
return 0;
}