Operator Overloading continued
A few rules:
+ - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= && || ++ -- ->* , -> [] () new delete
However, the following cannot be overloaded:
. .* :: ?: sizeof
It is not possible to change the number of operands that an operator takes
It is not possible to create new operators
The meaning of an operator for a built-in type cannot be changed
The functions for (), [], ->, or = MUST be declared as class members. For the other operators, they can be member or non-member functions.
Overloading the + and = operators, does not imply that += has been overloaded.
Two functions must be written to overload ++ (and --), since it can be used as either a post or pre increment (or decrement).
The prefix version is handled as any other prefix operator would be handled:
++object; becomes object.operator++(); //for member functions operator++(object); //for non-member functions
The postfix version presents a challange because it MUST have a different signature than the prefix version. To accomplish this, the postfix version's header has a dummy integer argument:
object++; becomes object.operator++(0); //for member functions operator++(object, 0); //for non-member functions Date Date::operator++() //pre-increment { helpIncrement(); return *this; } Date Date::operator++(int) //post-increment { Date temp = *this; helpIncrement(); //increment the one pointed to by this pointer return temp; //but return the non-incremented one (where the initial //value is saved } In a program: Date d(3, 18, 1969) cout << "Pre-increment:\n" << " d is " << d << "\n ++d is " << ++d << "\n d is " << d; cout << "\n\nPost-increment:\n" << " d is " << d << "\n d++ is " << d++ << "\n d is " << d; Will produce: Pre-increment: d is March 18, 1969 ++d is March 19, 1969 d is March 19, 1969 Post-increment: d is March 19, 1969 d++ is March 19, 1969 d is March 20, 1969