类运算符重载
这是一个非常基本的运算符重载问题。 假设我有一个像这样的类...
class xy
{
public:
double x, y;
XY(double X, double Y) { x = X; y = Y;}
XY operator+(const XY & add) const {
return XY(this->x + add.x, this->y + add.y);
}
XY & operator+=(const XY & add) const {?}
}
}
我希望operator+=做它应该做的事情(你知道,添加到x和y的当前值)。运算符+和运算符+=的代码不是相同的吗?
This is a very basic operator overload question.
Say I had a class like this...
class xy
{
public:
double x, y;
XY(double X, double Y) { x = X; y = Y;}
XY operator+(const XY & add) const {
return XY(this->x + add.x, this->y + add.y);
}
XY & operator+=(const XY & add) const {?}
}
}
And I want operator+= do to what its supposed to do (you know, add to the current value of x and y). Wouldn't the code be the same for operator+ and operator +=?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
怎么会一样呢?他们做不同的事情。
如果您不关心优化,可以在
+
运算符实现中使用+=
:How could it be the same? They do different things.
If you don't care about optimizations you can use
+=
in your+
operator implementation:是的,执行添加操作(坚持使用
+=
运算符),并返回对其自身的引用。哦,这不能是const
方法。Yep, do the add operation (stick to the
+=
operator), and return a reference to itself. Oh, and this can't be aconst
method.不会。按照惯例,
operator+
将结果存储在一个新对象中并按值返回它,而operator+=
将右侧添加到*this
并通过引用返回*this
。这两个运算符是相关的——并且通常可以相互实现——但它们具有不同的语义,因此不能具有相同的实现。
No. Conventionally,
operator+
stores the result in a new object and returns it by value, whereasoperator+=
adds the right-hand side to*this
and returns*this
by reference.The two operators are related -- and can often be implemented in terms of one another -- but they have different semantics and therefore can't have identical implementations.