cpp enum & enum class

enum是枚举类型就不多说了,用于自定义的数据。

现在说下enum和enum class有什么区别,为什么要用enum class。

enum有几种限制:
1.两个enum不能定义同样名称的数据,如下,会报重复定义的编译错误

// Defining enum1 Gender
 enum Gender { Male,
               Female };

 // Defining enum2 Gender2 with same values
 // This will throw error
 enum 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 Gender
 enum Gender { Male,
               Female };

 // Defining enum2 Color
 enum Color { Red,
              Green };

 // Creating Gender type variable
 Gender 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 actually
 if (gender == color)
     cout << "Equal";

猜猜这两个enum会相等吗?
答案是会的,会输出"Equal",这明明是两个不同的enum,但是enum里面的默认值是一样的。
但编译器会报warning信息

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

所以需要enum class,它有以下特点

使用时像下面这样

// Declaration
    enum class EnumName{ Value1, Value2};

// Initialisation
    EnumName 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 Class
    Color x = Color::Green;
 
    // Comparison now is completely type-safe
    if (x == Color::Red)
        cout << "It's Red\n";
    else
        cout << "It's not Red\n";
 
    People p = People::Good;
 
    if (p == People::Bad)
        cout << "Bad people\n";
    else
        cout << "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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值