Consider the following code:
#include<iostream>
enum week
{
sun=1,
mon,
tue,
wed,
thr,
fri,
sat
};
week &operator++(week& day,int)
{
if(day==sat)
day=sun;
else
day++; // This expression
return day;
}
int main()
{
week day=sun;
for(int i=0;i<=10;i++,day++)
{
std::cout<<day;
}
}
In the expression day++ it goes into infinite recursion.
If I cast it like ((int)day)++ the compiler gives the following error:
error: lvalue required as increment operand
If I change the line to day=week(((int)day)+1) it works. But how to fix the above code so it works with the ++ operator?
The default increment operator doesn't work well with enums. You'll have to overload the increment operator (with your week(((int)day)+1) logic) and handle the wrap-around in that overload function instead.
One way round the compiler error is to cast to a reference instead
((int&)day)++;
but you should take care that the backing type of the enum is an int:
enum week : int
{
// and so on
If that's not to your taste and would rather have the compiler decide the backing type for you then use
((std::underlying_type<week>::type&)day)++;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With