enumerations

Discussion in 'C++' started by scooter, Feb 7, 2007.

  1. scooter

    scooter Guest

    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
     
    scooter, Feb 7, 2007
    #1
    1. Advertising

  2. On Feb 7, 10:12 am, scooter <> wrote:

    > 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
     
    Thomas Tutone, Feb 7, 2007
    #2
    1. Advertising

  3. scooter

    Greg Herlihy Guest

    On 2/7/07 7:12 AM, in article ,
    "scooter" <> wrote:

    > 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
     
    Greg Herlihy, Feb 8, 2007
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. clintonG

    HttpStatusCode Enumerations...

    clintonG, May 5, 2004, in forum: ASP .Net
    Replies:
    4
    Views:
    3,953
    clintonG
    May 6, 2004
  2. exquisitus
    Replies:
    12
    Views:
    22,436
    Tilman Bohn
    Feb 19, 2005
  3. exquisitus
    Replies:
    2
    Views:
    452
    Tor Iver Wilhelmsen
    Apr 24, 2005
  4. Chanchal
    Replies:
    4
    Views:
    404
    Thomas Hawtin
    Nov 29, 2005
  5. Joyce
    Replies:
    1
    Views:
    2,087
    Stan Kitsis [MSFT]
    Feb 18, 2005
Loading...

Share This Page