enumerations

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • scooter

    enumerations

    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
  • Thomas Tutone

    #2
    Re: enumerations

    On Feb 7, 10:12 am, scooter <inva...@invali d.netwrote:
    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++(Ecol or& color)
    {
    // insert your code here to change color appropriately
    return color;
    }

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

    Best regards,

    Tom

    Comment

    • Greg Herlihy

      #3
      Re: enumerations

      On 2/7/07 7:12 AM, in article mtqjs2hrionk291 okn8ub8al87hdqr u7j2@4ax.com,
      "scooter" <invalid@invali d.netwrote:
      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


      Comment

      Working...