c++ 枚举类

在C++11及其后续版本中,引入了一个新的枚举类型称为“强类型枚举”或“枚举类”(enumeration class),通常简称为“枚举类”(enum class)。

相对于传统的枚举类型,枚举类有以下特点和优点:

  1. 强类型:枚举类的成员值不可以隐式转换为整数,也不能与整数值进行比较,除非显式地进行类型转换。
  2. 作用域:枚举类的成员值是限制在其枚举类作用域内的,所以不同的枚举类中可以有相同名称的成员。
  3. 明确指定底层类型:可以指定存储枚举成员的底层数据类型。

下面是一个enum class的例子:

enum class Color {
    Red,
    Green,
    Blue
};

enum class TrafficLight {
    Red,
    Yellow,
    Green
};

int main() {
    Color col = Color::Red;
    TrafficLight light = TrafficLight::Red;

    // 下面的代码是错误的,因为枚举类成员不能直接与整数比较
    // if(col == 0) {...}

    // 下面的代码也是错误的,因为不同的枚举类成员不能直接进行比较
    // if(col == light) {...}

    // 若要与整数比较,需要进行类型转换
    if(static_cast<int>(col) == 0) {
        // ...
    }

    return 0;
}

如果你想指定枚举类的底层类型,可以如下操作:

enum class Color : char {
    Red,
    Green,
    Blue
};

在上面的代码中,Color的底层类型被指定为char

枚举类(enum class)可以被用在switch语句中。使用枚举类在switch语句中有个好处:它使得代码更具可读性,因为你必须明确引用枚举的名称。不过,与传统的enum一样,如果你没有为switch语句处理所有的枚举值,编译器可能会给出警告(取决于编译器设置和所使用的编译器)。

以下是一个例子来展示如何在switch语句中使用enum class

#include <iostream>

enum class Color {
    Red,
    Green,
    Blue
};

void printColorDescription(Color color) {
    switch (color) {
        case Color::Red:
            std::cout << "Red is the color of fire and blood." << std::endl;
            break;
        case Color::Green:
            std::cout << "Green is the color of nature and life." << std::endl;
            break;
        case Color::Blue:
            std::cout << "Blue is the color of sky and sea." << std::endl;
            break;
        // 默认情况可以根据需要添加,但在此例中可能不是必需的
        // default:
        //     std::cout << "Unknown color." << std::endl;
    }
}

int main() {
    Color col = Color::Green;
    printColorDescription(col);
    return 0;
}

在上述代码中,我们定义了一个enum class Color,并在printColorDescription函数中使用switch语句来处理其不同的值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值