[英]How to use strongly typed enums
I'm not able to compile the following program: 我无法编译以下程序:
#include <iostream>
using namespace std;
enum class my_enum
{
ANT,
BAT,
CAT,
DOG,
EGG,
FAN,
MAX_MEMBERS
};
int main(int argc, char * argv[])
{
my_enum i = my_enum::ANT;
for(i = my_enum::ANT; i < my_enum::MAX_MEMBERS; i++)
{
cout << "Enum value = " << i << endl;
}
return 0;
}
I see the build error as follows: 我看到生成错误如下:
error: no 'operator++(int)' declared for postfix '++' [-fpermissive] for(i = my_enum::ANT; i < my_enum::MAX_MEMBERS; i++)
错误:没有为后缀'++'声明'operator ++(int)'[-fpermissive] for(i = my_enum :: ANT; i <my_enum :: MAX_MEMBERS; i ++)
Although incrementation operators are not defined for enumerated types by default, you can define your own, for instance: 虽然默认情况下未为枚举类型定义增量运算符,但是您可以定义自己的运算符,例如:
my_enum& operator++(my_enum& i)
{
assert(i < my_enum::MAX_MEMBERS);
i = static_cast<my_enum>(static_cast<int>(i)+1);
return i;
}
You can then write ++i in your loop and it will compile happily. 然后,您可以在循环中编写++ i,它将愉快地进行编译。
You are assuming that you can use my_enum as an int, but it now a new type. 您假设可以将my_enum用作int,但现在它是一种新类型。 So the "++" operator and the "<<" operator need to be defined for this type to work.
因此,需要定义“ ++”运算符和“ <<”运算符才能使此类型起作用。
A simple way to work around this is : 解决此问题的简单方法是:
#include <iostream>
using namespace std;
enum class my_enum
{
ANT,
BAT,
CAT,
DOG,
EGG,
FAN,
MAX_MEMBERS
};
int main( int argc, char * argv[] )
{
for ( my_enum i = my_enum::ANT; i < my_enum::MAX_MEMBERS; )
{
cout << "Enum value = " << (int)i << endl;
i = my_enum( (int)i + 1 );
}
return 0;
}
However, normally to iterate over an enum, typical code would be : 但是,通常迭代一个枚举,典型的代码是:
#include <iostream>
using namespace std;
enum my_enum
{
ANT,
BAT,
CAT,
DOG,
EGG,
FAN,
MAX_MEMBERS
};
int main( int argc, char * argv[] )
{
for ( int i = my_enum::ANT; i < my_enum::MAX_MEMBERS; i++ )
{
cout << "Enum value = " << i << endl;
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.