c++ - C++ 中成员的枚举成员,或替代

标签 c++ enums member variable-declaration

我想用C++创建一个enum,它的成员有成员。
我有一个类似的问题here ,但那一个处理的是 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 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;

关于c++ - C++ 中成员的枚举成员,或替代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32462912/

相关文章:

c++ - 为什么 C++ 没有指向成员函数类型的指针?

c++ - 拥有一个与非线程局部变量同名的线程局部变量是否可以?

c - 奇怪的枚举用法

java - 编译错误: constructor in class cannot be applied to given types

python-3.x - 在没有类名的 Python 中获取枚举名

c++ - 指向结构的指针的成员访问语法

C++ 静态模板成员,每种模板类型一个实例?

c++ - 如何通过 SWIG 将 lua 嵌入到 C++ 中

c++ - 使用 pugiXml 读取 XML 文档

c++ - 这是糟糕的风格吗?