与正常的枚举,

来源:互联网 发布:php mysql 集成安装包 编辑:程序博客网 时间:2024/03/29 13:24

与正常的枚举,枚举成员可以访问(如红色)直接在周边的范围(如在主)。然而,与枚举类,强作用域规则意味着你必须使用一个域限定符访问枚举器(例如:颜色:红色)。这有助于保持名称的污染和潜在的名称冲突

强类型规则意味着,C++将寻找一个明确定义的比较函数比较颜色和水果。因为我们还没有定义一个运算符= =(颜色水果)函数编译器不知道如何比较A和B的任何有意义的方式这将导致编译时错误发生

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
intmain()
{
    enumclass Color
    {
        RED,
        BLUE
    };
 
    enumclass 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;
 
    return0;

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

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


0 0
原创粉丝点击