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中