zoukankan      html  css  js  c++  java
  • cannot bind non-const lvalue reference of type 'std::__cxx11::string&

    1.问题

    类的构造函数定义为:

    Quote(std::string & s,double p):bookNo(s),price(p){}

    如果这样初始化对象:

    Quote q("123",10);

    就会报错误:

    cannot bind non-const lvalue reference of type 'std::__cxx11::string&

    而如果构造函数中的string添加了const,就不会报错了。

    2.解答

    https://stackoverflow.com/questions/18565167/non-const-lvalue-references,讲的很明白

    因为一个临时变量不能绑定到非const引用上。上面的例子中“123”就创建了一个临时string变量。

    但是这个也和编译器的版本有关,在VS中由于默认启用了编译器扩展,因此它可以正常工作。但是在GCC中会报错。

    https://blog.csdn.net/lisemi/article/details/103928596,这个说明了为什么临时变量不能绑定到非const引用上

    https://www.cnblogs.com/area-h-p/p/11498481.html

    如果一个参数是以非const引用传入,c++编译器就有理由认为程序员会在函数中修改这个值,并且这个被修改的引用在函数返回后要发挥作用。但如果你把一个临时变量当作非const引用参数传进来,由于临时变量的特殊性,程序员并不能操作临时变量,而且临时变量随时可能被释放掉,所以,一般说来,修改一个临时变量是毫无意义的,据此,c++编译器加入了临时变量不能作为非const引用的这个语义限制。

    3.例子

    std::string a[10]={
            "hello",
            "world",
            "shenzhen"
    };
    void print(std::string& str){
            std::cout << str << std::endl;
    }
    std::string get_string(int i){
            return a[i];
    }
    int main(){
            print(get_string(1));
            return 0;
    }

    会报错 error: cannot bind non-const lvalue reference of type

    因为get_string返回的是一个临时变量,可以解决的办法:

    1.print参数加上cosnt

    2.print参数去掉&

    3.get_string返回一个变量进行定义,再传入print中

  • 相关阅读:
    剑指Offer:数组中的逆序对
    Java高并发教程:Java NIO简介
    Java高并发教程:高并发IO的底层原理
    算法相关——Java排序算法之希尔排序(五)
    Materialized View模式
    Java技术——Java中的static关键字解析
    算法相关——Java排序算法之插入排序(四)
    Android Studio 2.2新增布局——ConstraintLayout完全解析
    公平锁与非公平锁
    Java线程和多线程(十五)——线程的活性
  • 原文地址:https://www.cnblogs.com/BlueBlueSea/p/14021491.html
Copyright © 2011-2022 走看看