何时使用枚举? [英] When to use enums?

查看:183
本文介绍了何时使用枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在阅读有关C.枚举我了解他们的工作,但不能揣摩出他们可能是有用的情况。
你能给我一些简单的例子,枚举的用法是合适的?

I'm currently reading about enums in C. I understand how they work, but can't figure out situations where they could be useful. Can you give me some simple examples where the usage of enums is appropriate?

推荐答案

枚举背后的概念有时也被称为枚举类型。也就是说,这是其所有可能值被命名和列为类型的定义的一部分的类型

The concept behind an enum is also sometimes called an "enumerated type". That is to say, it's a type all of whose possible values are named and listed as part of the definition of the type.

ç实际上是从一个位转移,因为如果 A B 是一个枚举值,则 A | b 也是该类型的有效值,不管它的上市并命名与否。但是,你不必使用这一事实,你可以使用一个enum只是作为一个枚举类型。

C actually diverts from that a bit, since if a and b are values in an enum, then a|b is also a valid value of that type, regardless of whether it's listed and named or not. But you don't have to use that fact, you can use an enum just as an enumerated type.

每当你想要一个变量,其可能的值每重新present一个事物的固定列表中的一个他们是合适的。他们有时也会在适当的时候要定义一堆相关的编译时间常数,特别是因为在C(与C ++),一个 const int的不是之前编制时间常数。

They're appropriate whenever you want a variable whose possible values each represent one of a fixed list of things. They're also sometimes appropriate when you want to define a bunch of related compile-time constants, especially since in C (unlike C++), a const int is not a compile-time constant.

我认为自己最有用的属性是:

I think that their most useful properties are:

1)您可以简明地定义一组不同的常数,你真的不关心什么值,只要它们是不同的。 的typedef枚举{红,绿,蓝彩} 优于:

1) You can concisely define a set of distinct constants where you don't really care what the values are as long as they're different. typedef enum { red, green, blue } color; is better than:

#define red   0
#define green 1
#define blue  2

2)一个程序员,在看到键入颜色的参数/返回值/可变的,知道什么样的价值观是合法的,他们的意思(或反正知道如何看该向上)。比使它成为 INT ,但记录这个参数必须在某些页眉或其他定义的颜色值中的一个。

2) A programmer, on seeing a parameter / return value / variable of type color, knows what values are legal and what they mean (or anyway knows how to look that up). Better than making it an int but documenting "this parameter must be one of the color values defined in some header or other".

3)您的调试器,在看见类型的变量颜色,也许可以做一个反向查找,并给红色作为值。比你看的了自己在源更好。

3) Your debugger, on seeing a variable of type color, may be able to do a reverse lookup, and give red as the value. Better than you looking that up yourself in the source.

4)编译器,在看到类型的前pression的开关颜色,可能警告你,如果没有默认和任何枚举值从情况 S的列表中丢失。这有助于避免在你正在做的事情为枚举的每个值不同的错误。

4) The compiler, on seeing a switch of an expression of type color, might warn you if there's no default and any of the enumerated values is missing from the list of cases. That helps avoid errors when you're doing something different for each value of the enum.

这篇关于何时使用枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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