10.3. Fundamentals of Operator Overloading

As you saw in Fig. 10.1, operators provide a concise notation for manipulating string objects. You can use operators with your own user-defined types as well. Although C++ does not allow new operators to be created, it does allow most existing operators to be overloaded so that, when they’re used with objects, they have meaning appropriate to those objects.

Operator overloading is not automatic—you must write operator-overloading functions to perform the desired operations. An operator is overloaded by writing a non-static member function definition or non-member function definition as you normally would, except that the function name starts with the keyword operator followed by the symbol for the operator being overloaded. For example, the function name operator+ would be used to overload the addition operator (+) for use with objects of a particular class (or enum). When operators are overloaded as member functions, they must be non-static, because they must be called on an object of the class and operate on that object.

To use an operator on an object of a class, you must define overloaded operator functions for that class—with three exceptions:

• The assignment operator (=) may be used with most classes to perform memberwise assignment of the data members—each data member is assigned from the assignment’s “source” object (on the right) to the “target” object (on the left). Memberwise assignment is dangerous for classes with pointer members, so we’ll explicitly overload the assignment operator for such classes.

• The address (&) operator returns a pointer to the object; this operator also can be overloaded.

• The comma operator evaluates the expression to its left then the expression to its right, and returns the value of the latter expression. This operator also can be overloaded.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.228.19