重载的“operator +”必须是一元或二元操作符错误 [英] overloaded 'operator+' must be a unary or binary operator error
问题描述
按照提供的建议这个回答,我重载了 +
操作符在我简单的 Point
类如下(+重载工作正常)。
Following the advice given in this answer, I have overloaded the +
operator in my simple Point
class as follows (the += overload works fine).
Point operator+ (Point p1, const Point& p2)
{
return std::move(p1 += p2);
}
但我收到一个错误,说
重载的'operator +'必须是一元或二元运算符(有3个参数)
overloaded 'operator+' must be a unary or binary operator (has 3 parameters)
什么是错的?
推荐答案
听起来你已经声明你的操作符是一个成员函数。成员函数接受隐式第一个参数,这意味着您的运算符现在需要三个参数。
It sounds like you have declared your operator as a member function. A member function takes an implicit first parameter, meaning your operator now takes three parameters. You can fix this by making it a non-member function.
在任何情况下,最好声明为非成员 ,以确保LHS和操作的RHS之间的对称性。
In any case, it is preferable to declare it as a non-member, to ensure symmetry between the LHS and the RHS of the operation.
对于标题中的实用程序/移动> std :: move
。虽然我看不到在这里使用它的原因。
As for std::move
, it is in the <utility>
header. Although I can't see the reason to use it here.
这篇关于重载的“operator +”必须是一元或二元操作符错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!