invalid initialization of non-const reference of type ‘xxx&’ from an rvalue of type ‘xxx’

来源:互联网 发布:小罗伯特唐尼 知乎 编辑:程序博客网 时间:2024/06/06 10:57

这是我在学习c++的过程中曾经遇到过的一条Linux环境下的编译错误
一开始不知道这个报错的意思是什么,debug半天没de出来,在网上阅博百篇,总算知道了这个报错的意思,一下就找出bug了。
因此直接将该报错信息作为标题以便后人搜索查阅。


  • 这个报错的中文意思是:非常量引用的初始值必须为左值(vs中的报错)


  • 最常见的原因有两种:

声明了一个针对常量的引用,例如

#include <iostream>using namespace std;int main(){    int& i = 10;//这种通常在vs里报错为:非常量引用的初始值必须为左值    /*在Linux便是invalid initialization of non-const reference of  type ‘int&’ from an rvalue of type ‘int’*/    return 0;}

解决办法

#include <iostream>using namespace std;int main(){    int x = 10;    int& i = x;    return 0;}

在参数为非常量引用类型的函数中传入常量类型,例如

#include <iostream>using namespace std;void fun(int& i){    cout << i;}int main(){    fun(1);//这种通常在vs里报错为:非常量引用的初始值必须为左值    /*在Linux便是invalid initialization of non-const reference of  type ‘int&’ from an rvalue of type ‘int’*/    return 0;}

又如

#include <iostream>#include <string>using namespace std;void fun(string& i){    cout << i;}int main(){    fun("str");//这种通常在vs里报错为:非常量引用的初始值必须为左值    /*在Linux便是invalid initialization of non-const reference of  type ‘string&’ from an rvalue of type ‘string’*/    return 0;}

解决办法均为在参数前面加个const关键字

#include <iostream>#include <string>using namespace std;void fun(const int& i){    cout << i;}int main(){    fun(1);    return 0;}
#include <iostream>#include <string>using namespace std;void fun(const string& i){    cout << i;}int main(){    fun("str");    return 0;}

所以,写代码养成随手加const是个好习惯,扼杀bug于编译的摇篮中。

阅读全文
0 0
原创粉丝点击