1、引用的基本使用
作用:给变量起别名
语法:数据类型(该数据类型要与原名的数据类型一致) &别名=原名;
示例:
#include<iostream>
using namespace std;
int main()
{int a = 10;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;
}
运行结果:
2、引用注意事项
(1)引用必须初始化,否则代码会报错
(2)引用初始化后,不可以改变
示例:
代码:
#include<iostream>
using namespace std;
int main()
{int a = 10;//引用必须初始化int& b;system("pause");return 0;
}
结果:
代码:
#include<iostream>
using namespace std;
int main()
{int a = 10;int& b = a;int c = 20;b = c;//赋值操作,而不是更改引用cout << "a=" << a << endl;cout << "b=" << b << endl;cout << "c=" << c << endl;system("pause");return 0;
}
结果:
3、引用做函数参数
作用:函数传参时,可以利用引用的技术让形参修饰实参
优点:可以简化指针修饰实参
以交换两个数为例:
代码:
#include<iostream>
using namespace std;
//值传递
void swap1(int a, int b)
{int temp = a;a = b;b = temp;
}
//地址传递
void swap2(int* a, int* b)
{int temp = *a;*a = *b;*b = temp;
}
//引用传递
void swap3(int& a, int& b)
{int temp = a;a = b;b = temp;}
int main()
{int a = 50;int b = 100;swap1(a, b);cout << "值传递a= " << a << " b= " << b << endl;swap2(&a, &b);cout << "地址传递a= " << a << " b= " << b << endl;/*swap3(a, b);cout << "引用传递a= " << a << " b= " << b << endl;*/system("pause");return 0;
}
执行结果:
代码:
#include<iostream>
using namespace std;
//值传递
void swap1(int a, int b)
{int temp = a;a = b;b = temp;
}
//地址传递
void swap2(int* a, int* b)
{int temp = *a;*a = *b;*b = temp;
}
//引用传递
void swap3(int& a, int& b)
{int temp = a;a = b;b = temp;}
int main()
{int a = 50;int b = 100;swap1(a, b);cout << "值传递a= " << a << " b= " << b << endl;/*swap2(&a, &b);*///cout << "地址传递a= " << a << " b= " << b << endl;swap3(a, b);cout << "引用传递a= " << a << " b= " << b << endl;system("pause");return 0;
}
结果:
从引用的代码结果可知,通过引用做函数参数同样可以实现:通过形参的改变从而改变实参。
总结:通过引用,参数产生的效果同地址传递是一样的,引用的语法更清楚简单。