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++ 中扩展枚举?


基础教程推荐
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01