Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator overloading for enum type

Tags:

c++

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?

like image 763
srilakshmikanthanp Avatar asked Jul 11 '26 02:07

srilakshmikanthanp


2 Answers

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.

like image 146
L. Scott Johnson Avatar answered Jul 13 '26 16:07

L. Scott Johnson


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)++;
like image 40
Bathsheba Avatar answered Jul 13 '26 15:07

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!