带有按引用传递的加法运算符

addition operator with pass by reference

本文关键字:运算符 按引用传递      更新时间:2023-10-16

我正在尝试重载加法运算符,使用以下原型:

obj operator+(obj&, obj&);

这适用于a+b但会在a+b+c上触发错误

G++ 会吐出以下错误:

test.cpp:17:6: error: no match for ‘operator+’ in ‘operator+((* & a), (* & b)) + c’
test.cpp:17:6: note: candidates are:
test.cpp:10:5: note: obj operator+(obj&, obj&)
error: no match for 'operator+' in 'operator+(obj&, obj&) 
note: candidates are: obj operator+(obj&, onj&) 

问题是你的参数是一个非常量引用,运算符返回一个新对象。

因此,a+b计算为临时对象,根据标准,该对象不能绑定到非const引用。因此,它不能作为参数传递给您的operator+。该解决方案最有可能按照@chris的建议使用const引用,因为您不应该修改 operator+ 的操作数。

没有人会预料到这一点,因此我个人认为这样做会很糟糕。

您可以假设方程的左侧始终引用"this"对象,这意味着您可以将重载运算符的签名更改为:

obj operator+(const obj &other){
    // Add value of "this" to value of other
    // Return obj
}