在C ++中扩展枚举? [英] Extending enums in C++?

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

问题描述

有没有方法在C ++中扩展/继承枚举?

Is there a way in C++ to extend/"inherit" enums?

IE:

enum Enum {A,B,C};
enum EnumEx : public Enum {D,E,F};

或至少定义它们之间的转换?

or at least define a conversion between them?

推荐答案

不,没有。

enum

即使是在C ++中引入的类枚举

Even the class enum introduced in C++0x does not address this extensibility issue (though they do some things for type safety at least).

枚举是它们不存在:它们提供某种类型的安全性,而不强加任何运行时开销,因为它们被编译器直接替换。

The only advantage of enum is that they do not exist: they offer some type safety while not imposing any runtime overhead as they are substituted by the compiler directly.

如果你想要这样的野兽,你必须自己工作:

If you want such a beast, you'll have to work yourself:


  • 创建一个类 MyEnum 包含一个int(基本上)

  • 为每个有趣的值创建命名构造函数

  • create a class MyEnum, that contains an int (basically)
  • create named constructors for each of the interesting values

现在可以扩展你的类(添加命名构造函数)在... ...

you may now extend your class (adding named constructors) at will...

这是一个解决方法,但我从来没有找到一个饱和的方式处理枚举...

That's a workaround though, I have never found a satistifying way of dealing with an enumeration...

这篇关于在C ++中扩展枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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