Download C++: A Beginner`s Guide, Second Edition

Transcript
it is necessary for operator=( ) to return the object pointed to by this, which will be the object that
occurs on the left side of the assignment statement. This allows a chain of assignments to be made. The
assignment operation is one of the most important uses of the this pointer.
In the preceding program, it was not actually necessary to overload the = because the default
assignment operator provided by C++ is adequate for the ThreeD class. (As explained earlier in this
module, the default assignment operation is a bitwise copy.) The = was overloaded simply to show the
proper procedure. In general, you need to overload the = only when the default bitwise copy cannot be
used. Because the default = operator is sufficient for ThreeD, subsequent examples in this module will
not overload it.
Order Matters
When overloading binary operators, remember that in many cases, the order of the operands does
make a difference. For example, although A + B is commutative, A – B is not. (That is, A – B is not the
same as B – A!) Therefore, when implementing overloaded versions of the noncommutative operators,
you must remember which operand is on the left and which is on the right. For example, here is how to
overload the minus for the ThreeD class:
Remember, it is the operand on the left that invokes the operator function. The operand on the right is
passed explicitly.
Using Member Functions to Overload Unary Operators
You can also overload unary operators, such as ++, – –, or the unary – or +. As stated earlier, when a
unary operator is overloaded by means of a member function, no object is explicitly passed to the
operator function. Instead, the operation is performed on the object that generates the call to the
function through the implicitly passed this pointer. For example, here is a program that defines the
increment operation for objects of type ThreeD:
32
C++ A Beginner’s Guide by Herbert Schildt