我有类型的颜色:
enum colors {green, red, blue};
colors mycolors=red
与int yourcolors=red
相同,是每个枚举器int
的类型吗?两者的值都是1,对吗?
谢谢!
答案 0 :(得分:2)
我只想发布一些代码片段来证明Jason Lang和Kerrek SB的评论:
#include <iostream>
#include <typeinfo>
enum colors {green, red, blue};
int main()
{
colors mycolors=red;
int yourcolors=red;
if (mycolors == yourcolors)
std::cout << "same values" << std::endl;
if (typeid(mycolors) != typeid(yourcolors))
std::cout << "not the same types" << std::endl;
return 0;
}
运行此代码将进入以下控制台输出:
same values
not the same types
另外(正如Daniel Kamil Kozar所提到的)有enum class
(只有C ++ 11及更高版本!)。有关enum class
优先于enum
的原因的详细信息,请参阅this Question。
关于'为什么enum
不仅仅是int
s(或long
s或...)之后的问题,只需考虑运算符重载。那是++ colors(green) == 1
一定不是真的。
确认this Question可以对普通enum
和this question and the accepted answer进行运算符重载,以了解如何避免在“枚举类”的重载运算符中进行转换。
最后请记住enum
s的使用 - 如果使用合理 - 可以提高代码的可读性。
答案 1 :(得分:1)
enum
似乎更加类型安全。您可以int yourcolors=red
,但不能colors mycolors=1
。enum KEYS
{
UP,
RIGHT,
DOWN,
LEFT
};
void (KEYS select)
{
switch (select)
{
case UP:
case RIGHT:
case DOWN:
case LEFT: break;
default: exit(1);
}
}