C++ 重载的“operator+”必须是一元或二元运算符错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13554320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
overloaded 'operator+' must be a unary or binary operator error
提问by learnvst
Following the advice given in this answer, I have overloaded the +
operator in my simple Point
class as follows (the += overload works fine).
按照此答案中给出的建议,我+
在我的简单Point
类中重载了运算符,如下所示(+= 重载工作正常)。
Point operator+ (Point p1, const Point& p2)
{
return std::move(p1 += p2);
}
But I get an error saying
但我收到一个错误说
overloaded 'operator+' must be a unary or binary operator (has 3 parameters)
重载的“operator+”必须是一元或二元运算符(有 3 个参数)
What is wrong?
怎么了?
回答by juanchopanza
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.
听起来您已将运算符声明为成员函数。成员函数采用隐式第一个参数,这意味着您的运算符现在采用三个参数。您可以通过使其成为非成员函数来解决此问题。
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.
在任何情况下,最好将其声明为非成员,以确保操作的 LHS 和 RHS 之间的对称性。
As for std::move
, it is in the <utility>
header. Although I can't see the reason to use it here.
至于std::move
,它在<utility>
标题中。虽然我看不到在这里使用它的原因。
回答by Drew Dormann
You want to do either:
您想要执行以下任一操作:
// Perform (*this + right)
Point operator+ (Point & right)
or
或者
// Perform (left + right) Friend functions have no "this".
friend Point operator+ (const Point &left, const Point& right)
回答by Lightness Races in Orbit
You made the operator a member function, meaning it actually has three parameters when you include the implicit first this
parameter.
您使运算符成为成员函数,这意味着当您包含隐式第一个this
参数时,它实际上具有三个参数。
Either:
任何一个:
- Use
*this
rather thanp1
and get rid of that first parameter, or - Make the operator overload a free function (instead of a member) — this is preferred.
- 使用
*this
而不是p1
去掉第一个参数,或者 - 使运算符重载为自由函数(而不是成员)——这是首选。