——傳統的列舉存在一些問題,其中之一是兩個列舉型別定義中的列舉量可能發生沖突,
enum egg {Small, Medium, Large, Jumbo};
enum t_shirt {Small, Medium, Large, Xlarge};
這將無法通過編譯(egg Small和t_shirt Small發生沖突)
解決辦法(新列舉):
C++11提供了一種新列舉,其列舉量的作用域為類:
enum class egg {Small, Medium, Large, Jumbo};
eum class t_shirt {Small, Medium, Large, Xlarge};
- 可使用關鍵字struct代替class
- 使用時需使用列舉名來限定列舉量:
egg choice = egg::Large; // the Large enumerator of the egg enum t_shirt Floyd = t_shirt::Large; // the Large enumerator of the t_shirt enum
- C++11提高了作用域內列舉的型別安全:
- 有時,常規列舉將自動轉換為整型,如將其賦給int變數或用于比較運算式時,但作用域內列舉不能隱式地轉換為整型:
enum egg_old {Small, Medium, Large, Jumbo}; // unscoped enum class t_shirt {Small, Medium, Large, Xlarge}; // scoped egg_old one = Medium; // unscoped t_shirt rolf = t_shirt::Large; // scoped int king = one; // implicit type conversion ofr unscoped int ring = rolf; // not allowed, no implicit type conversion if (king < Jumbo) // allowed std::cout<<"Jumbo converted to int before comparison.\n"; if (king < t_shirt::Medium) // not allowed std::cout<<"Not allowed: < not defined for scoped enum.\n";但在必要時,可顯示型別轉換:
int Frodo = int(t_shirt::Small); // Frodo set to 0
- 有時,常規列舉將自動轉換為整型,如將其賦給int變數或用于比較運算式時,但作用域內列舉不能隱式地轉換為整型:
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/17322.html
標籤:C++
上一篇:C++ 作用域為類的常量
