enumerations

S

scooter

say I have an enumeration:

enum Ecolor {eRed, eGreen, eBlue, eBrown, eNumColors};

and a variable:

Ecolor eCurrentColor = eGreen;

How can I increment or decrement eCurrentColor?

(since I can't just do eCurrentColor++)

thanks
 
T

Thomas Tutone

say I have an enumeration:

enum Ecolor {eRed, eGreen, eBlue, eBrown, eNumColors};

and a variable:

Ecolor eCurrentColor = eGreen;

How can I increment or decrement eCurrentColor?

(since I can't just do eCurrentColor++)

Create your own operator++ that takes an Ecolor:

Ecolor& operator++(Ecolor& color)
{
// insert your code here to change color appropriately
return color;
}

Ecolor operator++(Ecolor& color, int)
{
Ecolor temp = color;
++color;
return temp;
}

Best regards,

Tom
 
G

Greg Herlihy

say I have an enumeration:

enum Ecolor {eRed, eGreen, eBlue, eBrown, eNumColors};

and a variable:

Ecolor eCurrentColor = eGreen;

How can I increment or decrement eCurrentColor?

(since I can't just do eCurrentColor++)

Sure you can - assuming a suitable overloaded operator exists:

Ecolor operator++( Ecolor e, int)
{
return Ecolor(e + 1);
}

int main()
{
Ecolor eCurrentColor = eGreen;

eCurrentColor++; // OK
...
}

Of course it's a unclear what should happen when the last enumerated type is
incremented (should incrementing have no effect or should it "wrap around"
to the first enum?) Generally, a program should treat enums as distinct
categories of a type rather than as a range of numerical values.

Greg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,906
Latest member
SkinfixSkintag

Latest Threads

Top