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?
-
2This has a simple answer, but from the perspective of someone new to programming I can imagine this could be a source of much headache. +1Chris Lutz– Chris Lutz2010年03月21日 04:50:43 +00:00Commented Mar 21, 2010 at 4:50
2 Answers 2
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.:
T operator-()
and:
T operator-(const T &o)
The compiler chooses the right one based on the syntactical interpretation of the operator.
See also this useful set of guidelines.
2 Comments
Most unary operators can only be placed at a specified side of their operand. For the two special cases, ++ and --, see this FAQ.