Extending enums in C++?(在 C++ 中扩展枚举?)
问题描述
C++ 有没有办法扩展/继承"枚举?
Is there a way in C++ to extend/"inherit" enums?
即:
enum Enum {A,B,C};
enum EnumEx : public Enum {D,E,F};
或者至少定义它们之间的转换?
or at least define a conversion between them?
推荐答案
不,没有.
enum 在 C++ 中真的很糟糕,这当然是不幸的.
enum are really the poor thing in C++, and that's unfortunate of course.
即使是 C++0x 中引入的 class enum 也没有解决这个可扩展性问题(尽管它们至少为类型安全做了一些事情).
Even the class enum introduced in C++0x does not address this extensibility issue (though they do some things for type safety at least).
enum 的唯一优点是它们不存在:它们提供了一些类型安全性,同时不会强加任何运行时开销,因为它们被编译器直接替换.
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++ 中扩展枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中扩展枚举?
基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
