The overloaded operator version of the Time example begins with the class version of Time and modifies it to use overloaded operators for input, output, and addition. It still consists of three files, and each file requires some modification to complete the conversion to overloaded operators. Two versions of the example follow: The first version uses two member functions to implement the addition operation. In contrast, the second version uses only a single friend (i.e., non-member) function to complete the addition operation.
operator+ As a Member Function
The UML class diagram is converted to a C++ class as follows:
The read function introduced in chapter 5 and modified for chapter 6 could only read from the console. The read function did not have a parameter representing the source from which the function would read the data. Instead, the function hard-coded cout as the data source. So including the prompts in the read function itself was appropriate. The operator<< presented in Figure 4 retained the prompts to minimize the changes occurring to the function between chapters.
However, operator<< does include a parameter (the first one) denoting the data source. We can write a program that uses the operator interactively by asking an end-user to input data. However, we can also write a program that runs unattended, reading input from a file. In that case, there is no one to read and respond to the prompt, and the prompt can slow the program. I recommend moving the prompts to the application code (the client that uses the Time class) and adapting them as necessary. The following version of operator>> and in the driver appearing below illustrate this approach.
A simple driver program stands in for a Time client and demonstrates calls to the Time functions.
operator+ As a friend Function
The two operator+ functions defined in the example above can support two related, but distinct function calls:
Time + Time
Time + int
Mathematically, int + Time is also valid, but this function call does not match the argument list of either overloaded operator+ function. Furthermore, it is not possible write a version of operator+ as a member function that allows an int as the first argument (Figure 2). Fortunately, an appropriate operator+ function can be created as a non-member friend function. Furthermore, in conjunction with a conversion constructor, all three calling sequences may be satisfied with a single operator+ function (Figure 3).
The changes required to convert the Time class to use a friend function for operator+ are illustrated in the last two figures: