[英]Why does adding “const” solve “invalid operands to binary expression”
I have overloaded the operator + by Integer operator+(Integer & a, Integer & b)
. 我已经通过
Integer operator+(Integer & a, Integer & b)
重载了运算Integer operator+(Integer & a, Integer & b)
。 But when I do a=b+c+d , it gives the error of invalid operands to binary expression . 但是当我执行a = b + c + d时 ,它将无效操作数的错误赋予二进制表达式 。 But by adding
const
to the parameters, no more errors. 但是通过将
const
添加到参数中,不会再出现错误。 Why this happens? 为什么会这样?
b + c + d
generates a temporary for the result of b + c
. b + c + d
为b + c
的结果生成一个临时值。 A reference to that temporary is then passed to the second call to operator+
(). 然后,对该临时变量的引用将传递给对
operator+
()的第二次调用。
Only const
references can be bound to temporaries. 仅
const
引用可以绑定到临时对象。
For further discussion, see How come a non-const reference cannot bind to a temporary object? 有关更多讨论,请参见非常量引用为什么不能绑定到临时对象?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.