以下声明之间的区别

Difference between the following declarations?

本文关键字:区别 之间 声明      更新时间:2023-10-16

我有枚举类型,颜色:

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的更多信息,请参阅此问题。

关于"为什么enum s之后不仅仅是int s(或long s或......(的问题,只需考虑运算符重载。这是++ colors(green) == 1绝不能是真的。确认此问题,运算符重载对于普通enum s和此问题以及可接受的答案,以查看如何避免在"枚举类"的重载运算符中进行转换。

最后请记住,enum s的使用 - 如果使用合理 - 可以提高代码的可读性。

  • 我认为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);
    }
}