Enumeration class definition
format
enum class 枚举类型名:底层类型{
枚举值列表};
The default underlying type is int, but the underlying type can be customized in the new C++ standard.
Such as:
enum class Type {
General,Light,Medium,Heavy}; //底层类型默认是int型
enum class Type: char{
General,Light,Medium,Heavy};
enum class Category{
General=1,Pistol,MachineGun,Cannon};
Advantages of enumeration class
1. Strong scope: its scope is restricted to enumeration class, such as: use the enumeration value of Type General: Type::General
2. Conversion restriction: enumeration class object cannot be implicitly related to plastic Mutual conversion.
3. You can specify the underlying type, for example:
enum class Type:char{
General,Light,Medium,Heavy};
For example
#include <iostream>
using namespace std;
enum class Side{
Right,Left};
enum class Thing{
Wrong,Right}; //有相同的Right,但是不冲突,而两个不同的枚举类型有相同的枚举元素则会起冲突
int main()
{
Side s = Side::Right;
Thing w = Thing::Wrong;
cout << (s == w) << endl; //编译错误,无法直接比较不同的枚举类
system("pause");
return 0;
}