强烈的范围

本文探讨了C++11引入的枚举类特性,解释了传统枚举与枚举类的区别,特别是在类型安全性和防止不当比较方面的作用。通过示例展示了如何使用枚举类,并强调了其在提高代码质量和维护性方面的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;
 
int main()
{
    enum Color
    {
        RED,
        BLUE
    };
 
    enum Fruit
    {
        BANANA,
        APPLE
    };
 
    Color a = RED;
    Fruit b = BANANA;
 
    if (a == b) // The compiler will compare a and b as integers
        cout << "a and b are equal" << endl; // and find they are equal!
    else
        cout << "a and b are not equal" << endl;
 
    return 0;
}

当C + +比较A和B,这是比较他们为整数,这意味着在上面的例子中,一个确实等于B因为他们都默认为整数0。这是绝对没有希望从A和B是从不同的枚举!

C + + 11定义了一个新的概念,枚举类,使两个强类型的枚举和强烈的范围。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int main()
{
    enum class Color
    {
        RED,
        BLUE
    };
 
    enum class Fruit
    {
        BANANA,
        APPLE
    };
 
    Color a = Color::RED; // note: RED is not accessible any more, we have to use Color::RED
    Fruit b = Fruit::BANANA; // note: BANANA is not accessible any more, we have to use Fruit::BANANA
 
    if (a == b) // compile error here, as the compiler doesn't know how to compare different types Color and Fruit
        cout << "a and b are equal" << endl;
    else
        cout << "a and b are not equal" << endl;
 
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值