重载操作符命令
我有一个带有此运算符的 Point
对象:
Point operator +(float other) const {
return Point(x + other, y + other, z + other);
}
我可以像这样执行加法:
point + 10
但我无法以相反的顺序执行它:
10 + point
是否需要重载另一个运算符才能提供此功能?
Possible Duplicate:
Operator Overloading in C++ as int + obj
Operator overloading c++-faq
I have a Point
object with this operator:
Point operator +(float other) const {
return Point(x + other, y + other, z + other);
}
I can perform addition like so:
point + 10
But I can't perform it in reverse order:
10 + point
Is there another operator I need to overload in order to provide this functionality?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您通常希望重载全局运算符:
您可能只想使用一个重载,而不是两个重载:
然后使用一个构造函数从浮点数创建一个点:
在这种情况下,添加一个浮点数to a Point 将使用 ctor 将浮点转换为 Point,然后使用重载的运算符+将这两个点添加在一起。
You normally want to overload the global operator:
Instead of two overloads, you may want to use only one overload:
and then have a ctor to create a Point from a float:
In this case, adding a float to a Point will use the ctor to convert the float to a Point, then use your overloaded operator+ to add those two Points together.
作为免费功能:
As a free function:
给定一个现有的 Point& Point::operator+=(float other),添加这两个自由函数:
Given an existing
Point& Point::operator+=(float other)
, add these two free functions:课外:
Outside of the class: