//引用:取别名//语法:数据类型 &别名=原名#include<iostream>#include<string>usingnamespace std;intmain(){int a =10;int&b = a;
cout << a <<endl;//10
cout << b << endl;//10
b =100;
cout << a << endl;//100
cout << b << endl;//100
a =60;
cout << a << endl;//60
cout << b << endl;//60system("pause");return0;}
2、引用注意事项
#include<iostream>#include<string>usingnamespace std;intmain(){int a =10;//1、引用必须初始化//int &b; //错误,必须要初始化int&b = a;//2、引用在初始化后,不可以改变int c =20;
b = c;//赋值操作,而不是更改引用
cout << a << endl;//20
cout << b << endl;//20
cout << c<< endl;//20system("pause");return0;}
3、引用做函数参数
//引用做函数参数#include<iostream>#include<string>usingnamespace std;//1、值传递voidmySwap01(int a,int b){int temp = a;
a = b;
b = temp;//cout << a << endl;//cout << b << endl;}//2、地址传递voidmySwap02(int*a,int*b){int temp =*a;*a =*b;*b = temp;//cout << *a << endl;//cout << *b << endl;}//3、引用传递voidmySwap03(int&a,int&b){int temp = a;
a = b;
b = temp;
cout << a << endl;
cout << b << endl;}intmain(){int a =10;int b =20;//mySwap01(a, b);//mySwap02(&a,&b);mySwap03(a, b);
cout << a << endl;
cout << b << endl;system("pause");return0;}//总结//值传递:void mySwap01(int a, int b) mySwap01(a, b);//地址传递:void mySwap02(int *a, int *b) mySwap02(&a,&b);//引用传递:void mySwap03(int &a, int &b) mySwap03(a, b);
#include<iostream>#include<string>usingnamespace std;voidshowValue(constint&val){//val = 1000;加const不可修改
cout <<"val="<< val << endl;}intmain(){//常量引用//使用场景;用来修饰形参,防止误操作//int a = 10;//加上const之后 编译器将代码修改 int temp=10;const int &ref=temp;//const int &ref = 10;//引用必须引一块合法的内存空间int a =100;showValue(a);system("pause");return0;}