The operator++() function in the COUNTPP1 program has a subtle defect. You will discover it if you use a statement like this in main():
c1 = ++c2;
The compiler will complain. Why? Because we have defined the ++ operator to have a return type of void in the operator++() function, while in the assignment statement it is being asked to return a variable of type Counter. That is, the compiler is being asked to return whatever value c2 has after being operated on by the ++ operator, and assign this value to c1. So as defined in COUNTPP1, we can’t use ++ to increment Counter objects in assignments; it must always stand alone with its operand. Of course the normal ++ operator, applied to basic data types like int, would not have this problem.
To make it possible to use our homemade operator++() in assignment expressions, we must provide a way for it to return a value. The next program, countpp2, does just that.
Monday, September 22, 2008
Operator Return Values
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment