C++之invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
2017-03-21 16:54
483 查看
1、看代码
2、编译结果
3、分析和解决
就拿f(a + b)来说,a+b的值会存在一个临时变量中,当把这个临时变量传给f时,由于f的声明中,参数是int&,不是常量引用,因为c++编译器的一个关于语义的限制。如果一个参数是以非const引用传入,c++编译器就有理由认为程序员会在函数中修改这个值,并且这个被修改的引用在函数返回后要发挥作用。但如果你把一个临时变量当作非const引用参数传进来,由于临时变量的特殊性,程序员并不能操作临时变量,而且临时变量随时可能被释放掉,所以,一般说来,修改一个临时变量是毫无意义的,据此,c++编译器加入了临时变量不能作为非const引用的这个语义限制。修改:
或则函数参数引用加上const
4、总结
c++中临时变量不能作为非const的引用参数相关文章推荐
- C++引用报错:invalid initialization of non-const reference of type ‘std::string&’ from an rvalue of type
- C++引用报错:invalid initialization of non-const reference of type ‘std::string&’ from an rvalue of type
- invalid initialization of non-const reference of type ‘xxx&’ from an rvalue of type ‘xxx’
- invalid initialization of non-const reference of type ‘int*&’ from a temporary of type ‘int*’
- invalid initialization of non-const reference of type ‘int*&’ from a temporary of type ‘int*’
- error: invalid initialization of non-const reference of type ‘*&’ from a temporary of type
- 编译错误:error: invalid initialization of non-const reference of type ‘*&’ from a temporary of type
- invalid initialization of non-const reference of type与discards qualifiers
- C++ Error : initial value of reference to non-const must be an lvalue
- invalid initialization of non-const reference of type与discards qualifiers
- keil(MDK)中出现error: #513: a value of type "int" cannot be assigned to an entity of type "char *",即函数返
- INT_MAX Maximum value for an object of type int 32767 (215-1) or greater
- Bean property 'esyerDao' is not writable or has an invalid setter method. Does the parameter type of
- C++:invalid conversion from 'unsigned char *' to 'const char *'
- 类似Build Error: #513: a value of type "int" cannot be assigned to an entity of type "char *"
- 有关error:invalid type arguement of unary'*'(hava 'int')
- [C/C++]warning: format '%c' expects argument of type 'char*', but argument 2 has type 'int' [-Wforma
- The value of attribute "description" associated with an element type "target" must not contain the '<' character.
- spring Failed to convert property value of type 'java.lang.String' to required type 'int' for proper
- warning C4047: 'initializing' : 'char *' differs in levels of indirection from 'const int '