以下代码均可直接粘贴到编译器中测试
1.引用基本语法
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a=10;
//创建引用
int &b=a;
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
b=100;
//更改b的值等同更改a的值
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
}
2.引用注意事项
- 引用必须初始化
- 引用在初始化后,不可以改变
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a=10;
int &b=a;
//1.引用必须初始化
//int &b 错误,必须初始化
//2.引用在初始化后,不可以改变
int c=20;
b=c; //赋值操作,而不是更改引用
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
cout<<"c="<<c<<endl;
system("pause");
}
3.引用做函数参数
#include <iostream>
#include <string>
using namespace std;
//交换函数
//1.地址传递
void Swap01(int *a,int *b);
//2.引用传递
void Swap02(int &a,int &b);
int main()
{
int a=10;
int b=20;
Swap01(&a,&b);
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
Swap02(a,b);
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
system("pause");
}
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;
}
4.引用做函数的返回值
1)不要返回局部变量的引用
2)函数的调用可以作为左值
5.常量引用
#include <iostream>
#include <string>
using namespace std;
void showValue(int &v);
int main()
{
//常量引用
//使用场景,用来修饰形参,防止误操作
//加上const之后,编译器将代码修改
//int temp=10; const int &ref=temp;
//const int & ref=10; 引用必须引一块合法的内存空间
int a=100;
showValue(a);
system("pause");
return 0;
}
void showValue(const int &v)
{
cout<<"v="<<v<<endl;
}