[英]Difference between the following declarations?
我有枚举类型,颜色:
enum colors {green, red, blue};
colors mycolors=red
是否与int yourcolors=red
相同,并且每个枚举数的类型是否为int
? 两者的值都为1,对吧?
谢谢!
我只想发布一些代码片段来证明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
。
关于“为什么不只是int
(或long
或...)之后的enum
”的问题,请考虑运算符重载。 那就是++ colors(green) == 1
一定不正确。 确认以下问题 :对于普通enum
可能会发生运算符重载; 此问题以及已接受的答案,以了解如何避免在“枚举类”的重载运算符中进行强制转换。
最后要记住, enum
的用法(如果合理使用)会提高代码的可读性。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.