zoukankan      html  css  js  c++  java
  • C++ 非常量引用无效

    /* 非常量引用无效 */
    #include <iostream>
    
    using namespace std;
    
    /*
    C++标准的规定:非常量的引用不能指向临时对象:
    
    为了防止给常量或临时变量(只有瞬间的生命周期)赋值(易产生bug),只许使用const引用之。
    */
    
    class Student
    {
    public:
        Student(int num) :_num(num) 
        {
        }
    
    private:
        int _num;
    };
    
    void send(const Student & s)
    {
    }
    
    int test()
    {
        send(Student(10)); //error:用类型为‘Student’的右值初始化类型为‘Student&’的非常量引用无效
    
        /*
            分析:
                这里Student(10)的作用于仅限于send(),过了send()函数就会被释放,所以说Student(10)是一个临时对象
            C++标准的规定:非常量的引用不能指向临时对象,为了防止给常量或临时变量(只有瞬间的生命周期)赋值(易产生bug)
            ,只许使用const引用之。
            所以应该修改send(const Student & s);
            注意不加const,可能在vs中可以编译通过,但是在g++可能编译错误
    
        */
        return 0;
    }
    
    int main()
    {
        test();
        getchar();
        printf("ok
    ");
        return 0;
    }
  • 相关阅读:
    微信推送
    PS学习笔记
    汇编学习笔记
    JAVA学习笔记
    数组作为参数被传递,以及随机数的使用。
    [转]Win7系统中Telnet服务的安装和启动
    电脑高手学习笔记
    Android13.9.15
    C语言9.12
    《将博客搬至CSDN》
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/10339637.html
Copyright © 2011-2022 走看看