1.1 Operators are Functions
Operators are Functions
- Each operator is actually a shorthand for a
function named operator? where the ? is replaced by the actual operator
symbol.
- The function takes the same number and type of
parameters as does the operator
- The compiler translates the infix expressions
into the equivalent function calls
Examples: operators as functions
- If you write a +
b*(-c), that’s actually just a shorthand for
operator
+(
a
,
operator
*
(
b
,
operator
-
(
c
)))
- and if you write
that’s actually a shorthand for
operator
=(
testValue
,
operator
<=(
x
,
y
) ;
Declaring Operators
Understanding that shorthand, we can declare our
own operators by giving the appropriate operator function name:
class BidCollection {
⋮
void addInTimeOrder (const Bid& value);
Then
bids
.
addInTimeOrder
(
b
) ;
and
would do the same thing
Keep it Natural
- It’s easy to abuse operator overloading
and simply make things confusing.
- E.g., Don’t use operator+ unless your class really
does something "addition-like"
Most Commonly Overloaded Operators
There are, however, 3 groups of operators that
are very commonly overloaded
- I/O operators << >>
- Comparison operators < ==
- The assignment operator =
