zoukankan      html  css  js  c++  java
  • 引用

    引用与所代表的变量 共占一段内存 引用不占用内存 因此调用时非常快速并节省空间

    声明引用必须初始化(除作为参数和返回值)
    int &b=a;
    声明引用后,不可再被当做其他变量的引用
    int a1,a2;
    int &b1 = a1;
    b1 = a2; //ERROR


    指针变量也是变量 因此有指针变量的引用
    没有void 引用,引用的引用,指向引用的指针、引用数组、空引用
    需要指出的是 常量不能被引用 const int to int& is error
    const int to int const & is right


    指针的引用

    类型 *&指针引用名 = 指针;
    int n = 10;
    int *pn = &n;
    //int *&rn = &n //ERROR,右值只能是指针变量,不能为指针常量

    常引用 格式

    const 类型 & 引用名 = 变量名;
    类型 const & 引用名 = 变量名;
    含义:不能通过常引用修改变量的值

    注意:int & to const int & is right but const int & to int & is error
    int main()
    {
    int ival = 3;
    int &rival = ival;
    //int & to const int & is right
    const int &krrival = rival;
    引用赋值给常引用

    //const int& to int& is error
    //int &rrival = &krrival;
    常量不能起小名(除非也是常引用)
    return 0;
    }

    常引用可用为函数参数 不可改变其值 即不能作为左值

    引用作为形参时 对应实参必须是变量 不可为常量或者表达式


    引用作为函数返回值
    类型名 &函数名(形参表)
    可做左值 可做右值
    返回变量引用的函数 return 后面必须为变量,不能为常量或者表达式
    局部变量不能作为引用返回

    int &fun( int &x , int y )
    {
    … …
    return y;
    }
    结果不可预知

    常引用作为 返回值时 函数返回值类型 须为const 引用
    const int n = 3;
    const int &f( const int& m )
    {
    return m; //const int & to
    //int is Error
    }
    int main()
    {
    int a = 10;
    f(a);
    cout<<"a= "<<a<<endl;
    system("PAUSE");

    return 0;
    }

  • 相关阅读:
    LeetCode 动态规划专题
    LeetCode 双指针、滑动窗口、单调队列专题
    LeetCode 单调栈专题
    LeetCode DFS搜索与回溯专题
    LeetCode树专题
    操作系统思维导图| IO管理篇
    2020-为什么换了工作
    深入浅出Spring MVC
    rocketmq初识
    线上故障处理手册
  • 原文地址:https://www.cnblogs.com/newlist/p/2275391.html
Copyright © 2011-2022 走看看