cpp enum enum class
生活随笔
收集整理的這篇文章主要介紹了
cpp enum enum class
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
enum是枚舉類型就不多說了,用于自定義的數(shù)據(jù)。
現(xiàn)在說下enum和enum class有什么區(qū)別,為什么要用enum class。
enum有幾種限制:
1.兩個(gè)enum不能定義同樣名稱的數(shù)據(jù),如下,會(huì)報(bào)重復(fù)定義的編譯錯(cuò)誤
2.如果一個(gè)名稱在enum里,就不能再定義這個(gè)名稱的變量,如下,會(huì)報(bào)重定義的編譯錯(cuò)誤。
// 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";猜猜這兩個(gè)enum會(huì)相等嗎?
答案是會(huì)的,會(huì)輸出"Equal",這明明是兩個(gè)不同的enum,但是enum里面的默認(rèn)值是一樣的。
但編譯器會(huì)報(bào)warning信息
所以需要enum class,它有以下特點(diǎn)
使用時(shí)像下面這樣
// Declarationenum class EnumName{ Value1, Value2};// InitialisationEnumName ObjectName = EnumName::Value1;enum class會(huì)克服enum的上面列舉的限制
int main() {//相同的名稱可以出現(xiàn)在不同的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; }總結(jié)
以上是生活随笔為你收集整理的cpp enum enum class的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 越学越有趣:『手把手带你学NLP』系列
- 下一篇: 短视频下的世界