hangingfan / Technical-Blog

-----------------个人博客-----------------
1 stars 0 forks source link

C++ 枚举类型--限定作用域--scoped anumeration--strongly typed enumeration #13

Open hangingfan opened 6 years ago

hangingfan commented 6 years ago

现状: 使用没有限定作用域的枚举类型

enum [identifier] [: type]
{enum-list};

举例:

enum Suit { Diamonds, Hearts, Clubs, Spades };

缺点: 枚举成员和枚举类型本身的作用域相同, 导致如果另外一个枚举

enum OtherSuit{ Diamonds, Hearts, Clubs, Spades };      //wrong

就会报错, 因为成员冲突。

通常做法: 加额外的前缀或者后缀

enum OtherSuit{ Other_Diamonds, Other_ Hearts, Other_Clubs, Other_Spades };

现在有更好的做法:  使用限定作用域的枚举类型

enum [class|struct]
[identifier] [: type]
{enum-list};

enum class Suit { Diamonds, Hearts, Clubs, Spades };
enum class OtherSuit{ Diamonds, Hearts, Clubs, Spades };   ----right

细节 1: 作用域导致的使用方法不同 未限定作用域的枚举 Suit current = Diamonds;

限定作用域的枚举

Suit current = Suit::Diamonds

2: 枚举---> int 转换 未限定作用域的枚举, 可以隐式转换成int

enum unscopedPeppers{unscope1, unscope2, unscope3};
int i = unscope1;

限定作用域的枚举,只能显示转换成int

enum class peppers{red, yellow, green };
int j = static_cast<int>(peppers::green);

3: 默认类型 [: type] 未限定作用域的枚举, 如果没有指定潜在类型, 则枚举成员没有默认类型, 真正的类型因机器而异 限定作用域的枚举, 如果没有指定潜在类型, 则枚举成员默认为int类型

enum intValues :unsigned long long {
        charTyp = 255, shortTyp = 65535, intTyp = 65535,
        longType = 4394967295UL,
        long_longTyp = 18446744073709551615ULL
};

4: 前置声明 未限定作用域的枚举, 必须指定成员类型 限定作用域的枚举,没有这方面的要求(因为本身自带默认类型int)

enum intValues: unsigned long long;
enum class open_modes;

5.形参匹配----此处请参考相关书籍,不做展开