c++11中引入了新的枚舉類型---->強制枚舉類型
// unscoped enum: enum [identifier] [: type]
{enum-list}; // scoped enum: enum [class|struct] [identifier] [: type]
{enum-list};
identifier:
指定給與枚舉的類型名稱。
type:
枚舉器的基礎類型(默認int),所有枚舉器都具有相同的基礎類型,可能是任何整型。
enum-list:
枚舉中以逗號分隔的枚舉器列表。 范圍中的每個枚舉器或變量名必須是唯一的。 但是,值可以重復。 在未區分范圍的枚舉中,范圍是周邊范圍;在區分范圍的枚舉中,范圍是 enum-list 本身。
class:
可使用聲明中的此關鍵字指定枚舉區分范圍,並且必須提供 identifier。 還可使用 struct 關鍵字來代替 class,因為在此上下文中它們在語義上等效。
如下為兩者的簡單示例:
enum Test
{
test1,
test2
};
int a = test1; // 類型隱式轉換,枚舉常量無須限定
if (test1 == 0)
cout << "Hello world.";
enum class ErrorCode
{
ERROR_ONE,
ERROR_TWO,
ERROR_THREE
};
int num = 2;
num = static_cast<int>(ErrorCode::ERROR_ONE); // 類型需要顯示轉換,而且枚舉常量必須限定
ErrorCode test = static_cast<ErrorCode>(12); // 其實這個整數已經超出范圍了,但是居然合法
if (test == ErrorCode::ERROR_THREE)
cout << "It's impossible"