Sams Teach Yourself C++ in 21 Days

(singke) #1
varOne: 2
varTwo: 4
varThree: 6
operator+is declared on line 15 and defined on lines 28–31.

Compare these with the declaration and definition of the Add()function in the previous
listing; they are nearly identical. The syntax of their use, however, is quite different. It is
more natural to say this:
varThree = varOne + varTwo;
than to say:
varThree = varOne.Add(varTwo);
Not a big change, but enough to make the program easier to use and understand.
On line 36, the operator is used
36: varThree = varOne + varTwo;
This is translated by the compiler into
VarThree = varOne.operator+(varTwo);
You could, of course, have written it this way yourself, and the compiler would have
been equally happy.
The operator+method is called on the left-hand operand, passing in the right-hand
operand.

Issues in Operator Overloading ......................................................................


Overloaded operators can be member functions, as described in today’s lesson, or non-
member functions. The latter is described on Day 15, “Special Classes and Functions,”
when you learn about friend functions.
The only operators that must be class members are the assignment (=), subscript([]),
function call (()), and indirection (->) operators.
Operator []is discussed on Day 13, “Managing Arrays and Strings,” when arrays are
covered. Overloading operator ->is discussed on Day 15, when smart pointers are
discussed.

Limitations on Operator Overloading ............................................................


Operators for built-in types (such as int) cannot be overloaded. The precedence order
cannot be changed, and the arity of the operator, that is, whether it is unary or binary,

OUTPUT


316 Day 10


ANALYSIS
Free download pdf