枚举:两个不同的枚举常数为何可以有相同的整数值? [英] enum: why can two different enumeration-constants have the same integer value?

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

问题描述

我知道,如果我定义一个枚举平日是这样的:

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

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

然后,MON会内部等于0,默认情况下,和TUE 1,周三至2 ...

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

但是,如果我把它定义是这样的:

But if I define it this way:

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

那么这两个 MON 周二将得到的值为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 周二?或者说,哲学上说,两者兼而有之?

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

推荐答案

ç枚举是真正的整数 - 不仅仅是因为他们碰巧来实现这种方式,但因为标准的定义的枚举类型具有整数值。所以价值今天是真的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.

我想那么回答今天MON或TUE是是; - )

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天全站免登陆