I'm a newbie to C++ and especially C++11, so since I've now got to use it, a few questions about 'enum' and 'enum class' came up:

Can I assign values after the enumeration has been declared?

enum MyEnum;
MyEnum::HELLO = 0;
MyEnum::WORLD = 1;

Can I assign values to a number? (ex.: Myenum::0 = 2)

enum MyEnum;
MyEnum::0 = 16;
MyEnum::1 = 24;
MyEnum::3 = 64;

How does enum class work when using a struct or class as the underlying type?

Would the entries in the enumeration be valid instances of the struct/class?

class Test {
    private int v = 0;
    Test(int v) {
        this->v = v;
    }
};

enum class MyEnum : Test {
    Test0 = new Test(0),
    Test1 = new Test(1),
};

I found these links when I searched for the topic:

Which, as you can see, left a few questions.

有帮助吗?

解决方案

No. You cannot do any of those.

However, you may provide the definition the enum after its declaration as:

enum MyEnum; //declaration

enum MyEnum  //definition
{
  HELLO = 0,
  WORLD = 1;
};

Can I assign values to a number?

No. That doesn't make sense. A number already has a value. It is constant.


Please get an introductory book on programming in C++. Here are few recommendations :

其他提示

First of all, you cannot ever assign to a value in C++. The following is illegal:

42 = 23;

And for pretty much the same reason you cannot assign the value of an enum either.

Furthermore, you cannot even use the values of an enum after its declaration (i.e. you cannot write auto x = enum_name::name;), only after definition. You can only use the enum’s name.

Can I assign values to a number?

I’m not sure what this is supposed to mean but apart from what I’ve said before that syntax is illegal anyway. That is, you cannot access the second enum value by writing enum_name::1.

How does enum class work when using a struct or class as the underlying type?

You cannot use custom types as underlying types, only built-in integral types.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top