cpp enum enum class
生活随笔
收集整理的這篇文章主要介紹了
cpp enum enum class
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
enum是枚舉類型就不多說了,用于自定義的數據。
現在說下enum和enum class有什么區別,為什么要用enum class。
enum有幾種限制:
1.兩個enum不能定義同樣名稱的數據,如下,會報重復定義的編譯錯誤
2.如果一個名稱在enum里,就不能再定義這個名稱的變量,如下,會報重定義的編譯錯誤。
// Defining enum1 Gender enum Gender { Male,Female };// Creating Gender type variable Gender gender = Male;// creating a variable Male // this will throw error int Male = 10;3.enum是類型不安全的
// Defining enum1 Genderenum Gender { Male,Female };// Defining enum2 Colorenum Color { Red,Green };// Creating Gender type variableGender gender = Male;Color color = Red;// Upon comparing gender and color// it will return true as both have value 0// which should not be the case actuallyif (gender == color)cout << "Equal";猜猜這兩個enum會相等嗎?
答案是會的,會輸出"Equal",這明明是兩個不同的enum,但是enum里面的默認值是一樣的。
但編譯器會報warning信息
所以需要enum class,它有以下特點
使用時像下面這樣
// Declarationenum class EnumName{ Value1, Value2};// InitialisationEnumName ObjectName = EnumName::Value1;enum class會克服enum的上面列舉的限制
int main() {//相同的名稱可以出現在不同的enum class中enum class Color { Red,Green,Blue };enum class Color2 { Red,Black,White };enum class People { Good,Bad };// 可以定義變量名和enum class里的相同int Green = 10;// Instantiating the Enum ClassColor x = Color::Green;// Comparison now is completely type-safeif (x == Color::Red)cout << "It's Red\n";elsecout << "It's not Red\n";People p = People::Good;if (p == People::Bad)cout << "Bad people\n";elsecout << "Good people\n";// gives an error// if(x == p)// cout<<"red is equal to good";// won't work as there is no// implicit conversion to int// cout<< x;cout << int(x);return 0; }總結
以上是生活随笔為你收集整理的cpp enum enum class的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 越学越有趣:『手把手带你学NLP』系列
- 下一篇: 短视频下的世界