带有按引用传递的加法运算符
addition operator with pass by reference
我正在尝试重载加法运算符,使用以下原型:
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
}
相关文章:
- 按值传递变量与按引用传递变量具有相同的结果
- 获取 std::函数以推断按引用传递/按值传递
- C++/11 auto 关键字是在更有效时推导参数进行按引用传递,还是始终按值传递?
- 使用 enable_if 在按值传递与按引用传递之间更改函数声明
- 按引用传递和按地址传递之间的差异
- C++按引用传递还是按值传递?
- 可移动但不可复制的对象:按值传递还是按引用传递?
- 使用增量运算符按引用传递
- C++函数,按引用传递
- 按引用传递和动态内存分配之间的区别是什么
- 通过查看程序集来比较按值传递与按引用传递性能
- 在形式参数列表中自动使用 const 和按引用传递的任何明显后果
- 按引用传递函数参数
- C++按引用传递:如何使用调用堆栈
- 为什么按值传递 int 比按引用传递更快
- 是使用按引用传递来填充容器更好,还是使用返回值来填充容器更好
- 为什么 std::bind 在使用按引用传递时防止后期绑定?
- 带有按引用传递的加法运算符
- 按引用传递并使用引用运算符
- C++:使用 & 运算符进行按引用传递