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++)
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.
You are assuming that you can use my_enum as an int, but it now a new type. 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;
}
链接地址: http://www.djcxy.com/p/73068.html
上一篇: 运算符<<重载“错误:传递'const ....”
下一篇: 如何使用强类型枚举