12:
Operator
Overloading
Operator overloading
is just “syntactic
sugar,” which means it is
simply another way for you to make a function call.
The difference is that the arguments for
this function don’t appear inside parentheses, but instead they surround
or are next to characters you’ve always thought of as immutable
operators.
There are two differences between the use
of an operator and an ordinary function call. The syntax is different; an
operator is often “called” by placing it between or sometimes after
the arguments. The second difference is that the compiler determines which
“function” to call. For instance, if you are using the operator
+ with floating-point arguments, the compiler “calls” the
function to perform floating-point addition (this “call” is
typically the act of inserting in-line code, or a floating-point-processor
instruction). If you use operator + with a floating-point number and an
integer, the compiler “calls” a special function to turn the
int into a float, and then “calls” the floating-point
addition code.
But in C++, it’s possible to define
new operators that work with classes. This definition is just like an ordinary
function definition except that the name of the function consists of the keyword
operator followed by the operator. That’s
the only difference, and it becomes a function like any
other function, which the compiler calls when it sees the appropriate
pattern.
|