枚举与强类型枚举 [英] Enum vs Strongly typed enum

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

问题描述

我是C ++编程的初学者。

I am a beginner in C++ programming.

今天我遇到了一个新主题:强类型枚举。我已经研究了一点,但到现在我不能找到为什么我们需要这个和什么是同样的用途?

Today I come across a new topic: strongly typed enum. I've researched it a bit but till now I am unable to find out why do we need this and what is the use of the same?

例如,如果我们有:

enum xyz{a, b, c};
/*a = 0, b = 1, c = 2, (Typical C format)*/


$ b b

为什么我们需要写:

Why do we need to write:

enum class xyz{a, b, c};

我们在这里做什么?
我最重要的疑问是如何使用它。

What are we trying to do here? My most important doubt is how to use it. Could you provide a small example, which will make me understand.

推荐答案

OK,第一个例子:old-style枚举没有自己的范围:

OK, first example: old-style enums do not have their own scope:

enum Animals {Bear, Cat, Chicken};
enum Birds {Eagle, Duck, Chicken}; // error! Chicken has already been declared!

enum class Fruits { Apple, Pear, Orange };
enum class Colours { Blue, White, Orange }; // no problem!

其次,它们隐式转换为整数类型,这可能导致奇怪的行为:

Second, they implicitly convert to integral types, which can lead to strange behaviour:

bool b = Bear && Duck; // what?

最后,可以指定C ++ 11枚举的基本整数类型:

Finally, you can specify the underlying integral type of C++11 enums:

enum class Foo : char { A, B, C};

以前,未指定底层类型,这可能会导致平台之间的兼容性问题。 编辑在评论中已经指出,您还可以在C ++ 11中指定旧样式枚举的基本整数类型。

Previously, the underlying type was not specified, which could cause compatibility problems between platforms. Edit It has been pointed out in comments that you can also specify the underlying integral type of an "old style" enum in C++11.

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

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