简体   繁体   中英

How do I increment an enum in VS C++ 6.0?

I copy and pasted some code that increments an enum:

myenum++;  

This code worked fine as it was compiled in VS.NET C++ 2003

I am now developing in VS 6.0 and get the error:

error C2676: binary '++' : 'enum ID' does not define this operator or a conversion to a type acceptable to the predefined operator

How can I get this to behave the same in 6.0?

I see nothing wrong with defining operator++ on a well understood enum. Isn't that the purpose of operator overloading? If the context made no sense (eg an enum with holes in it), then of course it doesn't make sense. Defining operator* for a class called Complex that implement complex numbers is not just valid but a great application of mathematical operator overloading in C++!

If the developer defines an enum where operator++ makes obvious and intuitive sense to the clients of that enum, then that's a good application of that operator overload.

enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
inline DayOfWeek operator++(DayOfWeek &eDOW, int)
{
   const DayOfWeek ePrev = eDOW;
   const int i = static_cast<int>(eDOW);
   eDOW = static_cast<DayOfWeek>((i + 1) % 7);
   return ePrev;
}

an enum may be intergral but it doesn't mean it covers a continuous range.

This

enum {
  A, 
  B,
  C,
}

May Will default to

enum {
  A = 0, 
  B = A + 1,
  C = B + 1,
}

and so you could get away with

int a = A;
a++;

However if you have

enum {
  A = 2, 
  B = 4,
  C = 8,
}

now +1 ain't gonna work.

Now, if you also had things like

enum {
  FIRST,
  A = FIRST, 
  B,
  C,
  LAST = C
}

then when iterating the enum would you do A and C twice?

What is the purpose of iterating the enum? do you wish to do 'for all' or for some subset, is there actually an order to the enum?

I'd throw them all in a container and iterate that instead

  • unordered - use a set
  • ordered - a vector or list

请尝试转换为int,添加一个(+1)并转换回枚举。

myenum=(myenum_type)((int)myenum+1);

这很难看,但它确实有效。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM