Click to See Complete Forum and Search --> : increment operator problem
sszd
February 3rd, 2005, 09:25 PM
The following code does not compile, why?
1 int main ()
2 {
3 enum Day { Sun, Mon, Tue };
4
5 Day& operator++ (Day& d)
6 {
7 d = (Day) (d + 1);
8 return d;
9 }
10 }
Line 5 generates a compiler error similar to the following...
Unrecognized type name "Day"
This was compiled on a Sun box running Solaris 8 with their C++ compiler version 5.3.
Is there some fundamental problem with this code, or is this possibly a bug in the compiler?
HighCommander4
February 3rd, 2005, 10:00 PM
The problem is that you are attempting to overload and operator within a function. Operators can only be overloaded for class types, and the overloaded operator's declaration goes into the class declaration. That's not to mention that functions can't be defined inside other functions period...
sszd
February 3rd, 2005, 10:44 PM
I do not believe that is true. Read Bjarne Stroustrup's "The C++ Programming Language". There is a section that speaks of operating overloading for defined data types outside of a class. For definitions outside a class there is an additional argument that must be specified (as in this example). In fact, an example (using an enumeration) appears in his book, and is very similar to this example.
Paul McKenzie
February 3rd, 2005, 10:49 PM
I do not believe that is true.
Nested functions are not allowed in C++, and you have a nested function.
Regards,
Paul McKenzie
sszd
February 3rd, 2005, 10:53 PM
Ok, I'll buy that. Do you think it will compile if I move the enumeration and the operator++ function definition outside of main? Thanks for your help.
Paul McKenzie
February 3rd, 2005, 11:00 PM
Ok, I'll buy that. Do you think it will compile if I move the enumeration and the operator++ function definition outside of main? Yes.
Regards,
Paul McKenzie
Graham
February 4th, 2005, 03:57 AM
Note that overloading operator++(Day&) only gives you the prefix form of ++. For completeness, you should also implement the postfix form by overloading operator++(Day&, int). The second argument is not used - it's only there to distinguish the two forms.
And don't forget operator-- if appropriate.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.