简体   繁体   English

如何在VS C ++ 6.0中增加枚举?

[英]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 这段代码在VS.NET C ++ 2003中编译时效果很好

I am now developing in VS 6.0 and get the error: 我现在正在VS 6.0中开发并得到错误:

error C2676: binary '++' : 'enum ID' does not define this operator or a conversion to a type acceptable to the predefined operator 错误C2676:二进制'++':'枚举ID'未定义此运算符或转换为预定义运算符可接受的类型

How can I get this to behave the same in 6.0? 我怎样才能让它在6.0中表现相同?

I see nothing wrong with defining operator++ on a well understood enum. 我认为在一个易于理解的枚举上定义operator ++没有错。 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++! 为实现复数的复杂类定义operator *不仅有效,而且是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. 如果开发人员定义了一个枚举,其中operator ++对该枚举的客户端有明显的直观意义,那么这就是该运算符重载的一个很好的应用。

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. 现在+1不会起作用。

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? 然后在迭代枚举时你会做A和C两次吗?

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 ordered - 向量或列表

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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