简体   繁体   English

为什么添加“ const”可以解决“无效的操作数到二进制表达式”

[英]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 + db + 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.

相关问题 std::sort 中二进制表达式错误(缺少 const)的无效操作数:为什么指定比较运算符可以解决它? - Invalid operands to binary expression error (missing const) in std::sort: Why does specifying the compare operator solve it? 二进制表达式的无效操作数('RadioDevice'和'const RadioDevice') - Invalid operands to binary expression ('RadioDevice' and 'const RadioDevice') 如何解决这个问题? 二进制表达式的无效操作数 - How to solve this issue? Invalid operands to binary expression 无效的二进制二进制操作数(“ const Vector”和“ const Vector”) - Invalid operands to binary expression (‘const Vector’ and ‘const Vector’) 二进制表达式的无效操作数(常量点和常量点 - Invalid Operands to binary expression(const point and const point 二进制表达式的无效操作数? - invalid operands to binary expression? vector::erase 失败,二进制表达式的操作数无效(T 和 const T) - vector::erase fails with invalid operands to binary expression (T and const T) 无效的二进制操作数 - Invalid operands to binary expression 将节点添加到pirority队列(无效的操作数到二进制表达式) - adding nodes to pirority queue(invalid operands to binary expression) 错误:二进制表达式的操作数无效 - error: invalid operands to binary expression
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM