开发者

Enumeration type with some same values

Why declaration of two enums type wi开发者_开发技巧th same values in same block is not allowed in C++?

enum math_students {A,B,C};
enum comp_students {D,E,A}; // illegal


C++03 enum doesn't have tighter type checking under their scopes. So both math_students::A and comp_students::A can be simply referred as A. That's why they are not allowed in the same scope.

To overcome that you can enclose them in namespace or class.

namespace math_students {
  enum { A, B, C };
}
namespace comp_students {
  enum { D, E, A };  // ok
}

In C++11 you can use enum class (it has tighter type checking; and they don't get converted to int implicitly).

enum class math_students {A,B,C};
enum class comp_students {D,E,A};  // ok


The values in an enum are not scoped. The members of an enum are accessed directly by their names. So if multiple enums have members with the same name, there will be a naming comflict.


You can refer to the values by their names so it would be ambiguous.


Because you can refer these values without specifying an enum name.

math_students student = A;

In your case this will be ambiguous, so, the compiler doesn't allow that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜