Chapter 14. Overloaded Operations and Conversions
CONTENTS Section 14.1 Defining an Overloaded Operator506Section 14.2 Input and Output Operators513Section 14.3 Arithmetic and Relational Operators517Section 14.4 Assignment Operators520Section 14.5 Subscript Operator522Section 14.6 Member Access Operators523Section 14.7 Increment and Decrement Operators526Section 14.8 Call Operator and Function Objects530Section 14.9 Conversions and Class Types535Chapter Summary552Defined Terms552In Chapter 5 we saw that C++ defines a large number of operators and automatic conversions among the built-in types. These facilities allow programmers to write a rich set of mixed-type expressions.C++ lets us redefine the meaning of the operators when applied to objects of class type. It also lets us define conversion operations for class types. Class-type conversions are used like the built-in conversions to implicitly convert an object of one type to another type when needed.Chapter 13 covered the importance of the assignment operator and showed how to define the assignment operator. We first used overloaded operators in Chapter 1, when our programs used the shift operators (>> and <<) for input and output and the addition operator (+) to add two Sales_items. We'll finally see in this chapter how to define these overloaded operators.Through operator overloading, we can redefine most of the operators from Chapter 5 to work on objects of class type. Judicious use of operator overloading can make class types as intuitive to use as the built-in types. For example, the standard library defines several overloaded operators for the container classes. These classes define the subscript operator to access data elements and * and -> to dereference container iterators. The fact that these library types have the same operators makes using them similar to using built-in arrays and pointers. Allowing programs to use expressions rather than named functions can make the programs much easier to write and read. As an example, compare
to the more verbose code that would be necessary if IO used named functions:
cout << "The sum of " << v1 << " and " << v2
<< " is " << v1 + v2 << endl;
// hypothetical expression if IO used named functions
cout.print("The sum of ").print(v1).
print(" and ").print(v2).print(" is ").
print(v1 + v2).print("\n").flush();