引用的基本使用
    引用的作用:给地址取别名
    语法:数据类型 &名称 = 原名 (此处的数据类型和被引用的变量数据类型要一样)

    1. #include<iostream>
    2. using namespace std;
    3. int main (void){
    4. //引用的基本语法
    5. int a = 10;
    6. int &b = a;
    7. cout<<a<<endl;
    8. cout<<b<<endl;
    9. b = 20;
    10. cout<<a<<endl;
    11. system("pause");
    12. return 0;
    13. }

    注意:
    1.引用必须初始化
    2.引用在初始化之后就不能再改变了

    引用做函数参数
    作用:用引用技术传递函数参数
    优点:简化指针传递

    1. #include<iostream>
    2. using namespace std;
    3. void swap (int &a,int &b){
    4. int temp;
    5. temp = a;
    6. a = b;
    7. b = temp;
    8. }
    9. int main (void){
    10. //引用做函数传递
    11. int a = 10;
    12. int b = 20;
    13. swap(a,b);
    14. cout<<a<<endl<<b<<endl;
    15. system("pause");
    16. return 0;
    17. }

    引用做函数返回值:
    1.不能返回局部变量的引用(就像返回局部变量的地址一样,局部变量存放于栈区)
    2.函数调用可以作为左值

    1. //函数调用可以作为左值
    2. #include<iostream>
    3. using namespace std;
    4. int& test (void){
    5. static int a = 10;//静态变量在全局区
    6. return a;
    7. }
    8. int main (void){
    9. int &ref = test();
    10. cout << ref <<endl;
    11. test() = 100;//如果函数的返回值是一个引用,函数的调用可以作为左值。
    12. cout << ref <<endl;
    13. }

    引用的本质:
    引用的本质实际上是一个指针常量

    常量引用:在引用前添加const
    作用:修饰形参,防止误操作
    int &a = 10; 报错
    const int & ref = 10; 可以运行 ,编译器自动写成了
    int temp = 10;
    const int &ref = temp