枚举c++中成员的成员,或可选成员
enum members of members in C++, or alternative
我想用c++创建一个enum
,它的成员有成员。
我在这里有一个类似的问题,但那个问题是关于D的,而不是c++的。
在Python中,我可以这样做:
class Product(enum.Enum):
PHOTOSHOP = "Image editor.", 0
FIREFOX = "Web browser.", 1
NOTEPAD = "Text editor.", 2
def __init__(self, description, num):
self.description = description
self.num = num
>>> print(Product.PHOTOSHOP.description)
>>> "Image editor."
Java可以这样做:
public enum Product {
PHOTOSHOP("Image editor.", 0),
FIREFOX("Web browser.", 1),
NOTEPAD("Text editor.", 2);
private final String description;
private final int num;
Product(String description, int num) {
this.description = description;
this.num = num;
}
}
我可以在c++中这样做吗?
如果这种效果在c++中无法实现,那么还有什么好的替代方案呢?
据我所知,在c++中不能有多组件枚举,尽管我不自称是专家。
你能做的是声明一个enum,并使用它来查找数组中的字符串。
enum Product
{
PHOTOSHOP = 0,
FIREFOX,
NOTEPAD,
// must always be last
PRODUCT_ENUM_SIZE
};
const char* Product_Descriptions[PRODUCT_ENUM_SIZE];
Product_Descriptions[PHOTOSHOP] = "Image Editor";
Product_Descriptions[FIREFOX] = "Web Browser";
Product_Descriptions[NOTEPAD] = "Text Editor";
std::cout << "Firefox product number: " << FIREFOX << ". Description: " << Product_Descriptions[FIREFOX] << std::endl;
通过使用结构体而不是enum,您可以完成类似的操作:
struct Product
{
static constexpr struct type {const char* const description; const int num;}
PHOTOSHOP{"Image editor.", 0},
FIREFOX{"Web browser.", 1},
NOTEPAD{"Text editor.", 2};
};
不幸的是,您不能使用std::string
,因为它不是"文字"类型,因此不适合在constexpr
对象中使用。
另一个问题是枚举数的类型是Product::type
,而不仅仅是Product
,这将影响需要声明变量的任何代码。在使用内联定义的同时,条目的类型与包含它们的类型是不可能的。
我意识到它没有回答这个问题,但是一个功能完整的枚举不可避免地需要传递对单例的引用,而不仅仅是一个值(从而影响代码的空间局部性)。这不是c++的方式。
c++的方法是只在必要的时候付出代价。例如:
enum class X { ... };
char const* to_str(X x) { return lookup_value_in_static_map(x);}
X from_str(char const* v)
ostream& operator <<(ostream& out, X x) { return out << to_str(x); }
如果需要,可以通过一些简单的调整使上面的代码在编译时友好。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将函数类成员映射到类本身内部
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- 多成员Constexpr结构初始化
- 我们可以访问一个不存在的联盟的成员吗