srilakshmikanthanp
srilakshmikanthanp

Reputation: 2399

operator overloading for enum type

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?

Upvotes: 3

Views: 562

Answers (3)

Bathsheba
Bathsheba

Reputation: 234875

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)++;

Upvotes: 4

Hawky
Hawky

Reputation: 440

(int)day returns an int, which you try to increment by ++ operator. So basically you do something like ... = 5++ which is not legal.

Upvotes: 4

L. Scott Johnson
L. Scott Johnson

Reputation: 4412

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.

Upvotes: 5

Related Questions