为什么两个不同的枚举枚举常量具有相同的整数值? [英] Why can two different enum enumeration-constants have the same integer value?

查看:318
本文介绍了为什么两个不同的枚举枚举常量具有相同的整数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,如果我这样定义枚举工作日:

I know that if I defined an enum weekday like this:

enum weekday {
    MON,
    TUE,
    WED,
    THU,
    FRI,
};

然后,默认情况下,MON内部默认为0,TUE为1,WED为2。 ..

Then, MON would internally equal to 0, by default, and TUE to 1, WED to 2...

但是如果我这样定义:

enum weekday {
    MON,
    TUE = 0,
    WED,
    THU,
    FRI,
};

然后同时 MON TUE 的值为0。

系统如何在内部区分MON和TUE?我的意思是,如果我声明这样的话:

How would a system differentiate MON and TUE internally? I mean, if I declare something like this:

enum weekday today = 0;

那么今天是 MON TUE ?或者,从哲学上来说,两者都是?

Then is today MON or TUE? Or, philosophically speaking, both?

推荐答案

C枚举是真正的整数-不仅仅是因为它们恰好被实现为的方式,但是因为标准定义枚举类型具有整数值。因此,今天 的值实际上是 0。发生的一切是您为值0创建了两个不同的名称。

C enums are "really" integers -- not just because they happen to be implemented that way, but because the standard defines enum types to have integer values. So the value of today is "really" 0. All that has happened is that you've created two different names for the value 0.

我认为,今天是星期一还是星期二的答案是是;-)

I suppose then that the answer to "is today MON or TUE" is "yes" ;-)

语言不会阻止您因为有时对于枚举而言,具有多个相同值的名称很有用。例如:

The language doesn't stop you because occasionally it's useful for an enum to have multiple names for the same value. For example:

enum compression_method {
    COMP_NONE = 0,
    COMP_LOW = 1,
    COMP_HIGH = 2,
    COMP_BEST = 2,
    COMP_FASTEST = 0,
};

这篇关于为什么两个不同的枚举枚举常量具有相同的整数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆