There are several unary operators including:
++( ) // pre increment --( ) // pre decrement ( )++ // post increment ( )-- // post decrement -( ) // opposite +( ) // same as
Each of these operators must have only one operand and it must be an object of the class.
While these operators would not make sense on all classes, the first four of them would on the class Date. Where ++() or ()++ should mean tomorrow and --() or ()-- should mean yesterday.
For example, the following statements:
Date today(12,31,2006); ++today;
should make the Date object: today be the Date object: 1/1/2007 after these two statements. (Recall that ++today really means today.++().)
For another example:
Date today(1,1,2006); --today;
should make today become the Date object: 12/31/2005 after these two statements. (Recall that --today really means today.--().) For an example of these operators in a complete program see: futrpas2.cpp.
As stated above, operators may be either a member or a non-member function. For an example of a non-member operator see: futrpas1.cpp. That example may have been unsatisfactory because the data members are public. However, it is possible to have non-member operators with private members. For example see: futrpas3.cpp.
Each of the previous examples used pre-unary operators. What about post-unary operators? For this see futrpas4.cpp. The post-unary operators in that example do not have a separate definition and in fact they are not true post-unary operators.
Earlier C++ compilers did not distinguish between pre-unary and post-unary operators. This made it difficult to use these operators in expressions. In that case there was no difference between:
b = ++a + value;
and
b = a++ + value;
The newer compilers distinguish between these two by defining the post with a "dummy" int argument (i.e. it is never used in the function body) permitting both the pre and post unary operators to exist. For example, the pre-unary ++( ) could be defined as:
datatype operator classname::++( ){....}
while the post-unary ( )++ could be defined as:
datatype operator classname::++(int neverused) {....}
where neverused is an int variable but not a keyword. For an example of defining the post operators using this approach see futrpast.cpp. (In this example notice that the argument uses notused instead of neverused i.e. any variable name would work).
When ++( ) is a member function, you would expect the code to be:
date theDate; theDate.++( );
However the language permits the following:
date theDate; ++theDate;
Regardless of whether the function is a nonmember function with an explicit argument or a member function with the implicit argument, the construct is still the same as the following table shows:
Is Member? | Code Written [*], | Actual Call |
---|---|---|
YES | OP A | A.OP( ) |
YES | A OP | A.OP( ) |
NO | OP A | OP(A ) |
NO | A OP | OP(A) |
[*]where OP is the unary operator and A is the class object. |