C++ 中的运算符重载
如果你重载-像operator-()一样,它会被用在对象的左边,但是重载()像operator()()一样它会被用在对象的右边。我们如何知道哪个运算符应该用在左边,哪个运算符应该用在右边?
If you overload - like operator-(), it is to be used to the left of the object, however overloading () like operator()() it is used to the right of the object. How do we know which operator is to be used on the left and which ones to be used on the right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请查看运算符优先级图表。这将告诉您操作员关联(绑定)的方向。请注意,某些运算符具有具有不同含义的多种形式,例如二元和一元
-
。在这种情况下,您可能有多个重载,例如:and:
编译器根据运算符的语法解释选择正确的重载。
另请参阅这套有用的一套指南。
Look at the operator precedence chart. This will tell you the direction the operator associates (binds). Note that some operators have multiple forms with different meanings, such as binary and unary
-
. In such cases, you may have multiple overloads, e.g.:and:
The compiler chooses the right one based on the syntactical interpretation of the operator.
See also this useful set of guidelines.
大多数一元运算符只能放置在其操作数的指定一侧。对于两种特殊情况
++
和--
,请参阅 此常见问题解答。Most unary operators can only be placed at a specified side of their operand. For the two special cases,
++
and--
, see this FAQ.