您的位置:首页 > 编程语言 > C语言/C++

C++引用报错:invalid initialization of non-const reference of type ‘std::string&’ from an rvalue of type

2018-01-13 14:54 2371 查看

一、

invalid initialization of non-const reference of type ‘std::string&’ from an rvalue of type ‘std::string’
#include<iostream>
#include<string>
using std::cout;
using std::string;
using std::endl;
void PrintStr(std::string& str);
int main()
{
    PrintStr(string("HelloWorld!"));   //string("HelloWorld!")  为一个临时变量
    return 0;
}
void PrintStr(std::string& str)
{
    cout<< str << endl;
}
说明:临时变量是转瞬即逝的,在上面的代码中,用str引用临时变量的时候临时变量已经不存在了。
解决方案:void PrintStr(std::string& str);改为void PrintStr(const std::string& str);

二、


1、看代码




2、编译结果






3、分析和解决

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

修改:



或则函数参数引用加上const




4、总结

c++中临时变量不能作为非const的引用参数 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐