枚举C ++中的成员或替代成员

时间:2015-09-08 16:34:23

标签: 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 ++中无法实现这种效果,那么有什么好的选择?

3 个答案:

答案 0 :(得分:1)

据我所知,你不能在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;

答案 1 :(得分:1)

通过转到结构而不是枚举,您可以完成类似的事情:

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,因为它不是&#34;字面值&#34;类型,因此不适用于constexpr个对象。

另一个问题是枚举的类型是Product::type,而不仅仅是Product,这将影响您需要声明变量的任何代码。它只是不可能使用内联定义,并且项目的类型与包含它们的类型相同。

答案 2 :(得分:1)

我意识到它没有回答这个问题,但是一个功能齐全的枚举不可避免地需要传递对单例的引用而不仅仅是一个值(从而影响代码的空间局部性)。那不是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); }

如果需要,可以通过一些简单的调整使编译时友好。

相关问题