日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

cpp enum enum class

發布時間:2023/12/8 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 cpp enum enum class 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

enum是枚舉類型就不多說了,用于自定義的數據。

現在說下enum和enum class有什么區別,為什么要用enum class。

enum有幾種限制:
1.兩個enum不能定義同樣名稱的數據,如下,會報重復定義的編譯錯誤

// Defining enum1 Genderenum Gender { Male,Female };// Defining enum2 Gender2 with same values// This will throw errorenum Gender2 { Male,Female };

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信息

warning: comparison between ‘enum main()::Gender’ and ‘enum main()::Color’

所以需要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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。