|
||
Lesson 9
Objective
|
Overloading binary operators
Write member functions to overload binary operators. |
|
|
We continue with our clock example and show how to overload binary operators. Basically, the same principles hold.
Symmetrical Binary Operators
When a binary operator is overloaded using a member function, it has
When a binary operator is overloaded using a friend or nonmember function, both arguments are specified in the parameter
list.
Remember, though, that nonmember functions that are not friend functions cannot access private members of a class. Create an operation for clock that will add two values together.
class clock {
.....
friend clock operator+(clock c1, clock c2);
};
clock operator+(clock c1, clock c2)
{
return (c1.tot_secs + c2.tot_secs);
}
The integer expression is implicitly converted to a clock by the conversion constructor clock::clock(unsigned
long). Both clock values are passed as function arguments, and both are candidates for assignment conversions. Because
operator+() is a symmetrical binary operator, the arguments should be treated identically.
Overloading Binary Operators - Exercise
Thus, it is normal for symmetrical binary operators to be overloaded by friend functions.
Click the Exercise button to try your hand at overloading several arithmetic binary operators in a class that implements a set.
Overloading Binary Operators - Exercise |
||
|
|
||