C++ - 介绍enum的使用

在 C++ 中,枚举关键字用于定义枚举,枚举是一种用户定义的数据类型,由一组命名的积分常量组成。枚举可以用有意义的名称来表示相关常量的集合,从而提高代码的可读性和可维护性。

In C++, the enum keyword is used to define an enumeration, which is a user-defined data type consisting of a set of named integral constants. Enumerations are useful for representing a collection of related constants with meaningful names, improving code readability and maintainability.

Basic Enum Definition

Here’s how you can define and use a basic enumeration in C++:

#include <iostream>

// Define an enum outside of any class

enum Color {

    RED,

    GREEN,

    BLUE

};

int main() {

    // Declare a variable of type Color

    Color myColor = RED;

    // Use the enum variable in a switch statement

    switch (myColor) {

        case RED:

            std::cout << "The color is RED" << std::endl;

            break;

        case GREEN:

            std::cout << "The color is GREEN" << std::endl;

            break;

        case BLUE:

            std::cout << "The color is BLUE" << std::endl;

            break;

        default:

            std::cout << "Unknown color" << std::endl;

            break;

    }

    return 0;

}

Scoped Enumerations (enum class)

在 C++11 及更高版本中,可以使用 enum class(或 enum struct)定义作用域枚举。作用域枚举提供了更好的类型安全性,并防止了全局命名空间的污染。

In C++11 and later, you can define scoped enumerations using enum class (or enum struct). Scoped enumerations provide better type safety and prevent pollution of the global namespace.

#include <iostream>

// Define a scoped enum (enum class)

enum class Color {

    RED,

    GREEN,

    BLUE

};

int main() {

    // Declare a variable of type Color

    Color myColor = Color::RED;

    // Use the enum variable in a switch statement

    switch (myColor) {

        case Color::RED:

            std::cout << "The color is RED" << std::endl;

            break;

        case Color::GREEN:

            std::cout << "The color is GREEN" << std::endl;

            break;

        case Color::BLUE:

            std::cout << "The color is BLUE" << std::endl;

            break;

        default:

            std::cout << "Unknown color" << std::endl;

            break;

    }

    return 0;

}

Enum Inside a Class

你可以在类内定义一个枚举,以便在类范围内封装相关常量:

You can define an enum inside a class to encapsulate related constants within the class scope:

#include <iostream>

class MyClass {

public:

    // Define an enum inside the class

    enum Color {

        RED,

        GREEN,

        BLUE

    };

    // Method to demonstrate usage of the enum

    void printColor(Color color) {

        switch (color) {

            case RED:

                std::cout << "Color is RED" << std::endl;

                break;

            case GREEN:

                std::cout << "Color is GREEN" << std::endl;

                break;

            case BLUE:

                std::cout << "Color is BLUE" << std::endl;

                break;

            default:

                std::cout << "Unknown color" << std::endl;

                break;

        }

    }

};

int main() {

    MyClass myObject;

    // Use the enum defined in the class

    myObject.printColor(MyClass::RED);

    myObject.printColor(MyClass::GREEN);

    myObject.printColor(MyClass::BLUE);

    return 0;

}

Scoped Enum Inside a Class

还可以在类内定义一个作用域枚举(枚举类),以提高类型安全性:

You can also define a scoped enum (enum class) inside a class for better type safety:

#include <iostream>

class MyClass {

public:

    // Define a scoped enum inside the class

    enum class Color {

        RED,

        GREEN,

        BLUE

    };

    // Method to demonstrate usage of the enum

    void printColor(Color color) {

        switch (color) {

            case Color::RED:

                std::cout << "Color is RED" << std::endl;

                break;

            case Color::GREEN:

                std::cout << "Color is GREEN" << std::endl;

                break;

            case Color::BLUE:

                std::cout << "Color is BLUE" << std::endl;

                break;

            default:

                std::cout << "Unknown color" << std::endl;

                break;

        }

    }

};

int main() {

    MyClass myObject;

    // Use the scoped enum defined in the class

    myObject.printColor(MyClass::Color::RED);

    myObject.printColor(MyClass::Color::GREEN);

    myObject.printColor(MyClass::Color::BLUE);

    return 0;

}

Summary

* 基本枚举: 使用枚举定义一组简单的相关常量。

* 作用域枚举: 使用枚举类可以提高类型安全性,避免命名空间污染。

* 类中的枚举: 在类中定义枚举,将其封装在类范围内。

* 类中的作用域枚举: 在类中使用枚举类,以实现封装和类型安全。

* Basic Enum: Use enum to define a simple set of related constants.

* Scoped Enum: Use enum class for better type safety and to avoid namespace pollution.

* Enum in Class: Define enums inside a class to encapsulate them within the class scope.

* Scoped Enum in Class: Use enum class inside a class for encapsulation and type safety.

= = = = = = = = = = = = 分割线 = = = = = = = = = = = =

Enumeration declaration - cppreference.com

枚举是一种独特的类型,其值仅限于一个值范围(详见下文),其中可能包括几个明确命名的常量("枚举器")。

常量的值是被称为枚举底层类型的整形类型的值。枚举的大小、值表示和对齐要求与其基础类型相同。此外,枚举的每个值都与底层类型的相应值具有相同的表示形式。

An enumeration is a distinct type whose value is restricted to a range of values (see below for details), which may include several explicitly named constants ("enumerators").

The values of the constants are values of an integral type known as the underlying type of the enumeration. An enumeration has the same size, value representation, and alignment requirements as its underlying type. Furthermore, each value of an enumeration has the same representation as the corresponding value of the underlying type.

Declaration:

enum-key attr (optional) enum-head-name (optional) enum-base (optional) { enumerator-list , };

可以在枚举器列表后加上逗号。

A trailing comma can follow the enumerator-list.

声明之后,该类型就是一个完整的类型.

After this declaration, the type is a complete type.

enum-key:

enum (until C++11)

one of enum, enum class, or enum struct (since C++11)

enum-head-name:

要声明的枚举的名称,可以省略。

The name of the enumeration that's being declared, it can be omitted.

enum-base:

(自 C++11 起)冒号(:),后跟一个 type-specifier-seq,命名一个整形类型,作为该枚举类型的固定基础类型。

(since C++11) colon (:), followed by a type-specifier-seq that names an integral type that will serve as the fixed underlying type for this enumeration type

格式如下:

enum struct|class name : type { enumerator = constant-expression , enumerator = constant-expression , ... }

type可以是unsigned char,std::uint32_t等。

例如:

enum class Handle : std::uint32_t { Invalid = 0 };

enumerator-list:

用逗号分隔的枚举器定义列表,每个枚举器定义都是一个唯一标识符(成为枚举器的名称),或者是一个带有常量表达式的唯一标识符:identifier = constant-expression。

Comma-separated list of enumerator definitions, each of which is either simply a unique identifier, which becomes the name of the enumerator, or a unique identifier with a constant expression: identifier = constant-expression.

枚举有两种不同的类型:非作用域枚举(使用 enum-key enum 声明)和作用域枚举(使用 enum-key enum class 或 enum struct 声明)。

There are two distinct kinds of enumerations: unscoped enumeration (declared with the enum-key enum) and scoped enumeration (declared with the enum-key enum class or enum struct).

Unscoped enumerations

enum name (optional) { enumerator = constant-expression , enumerator = constant-expression , ... }

enum name (optional) : type { enumerator = constant-expression , enumerator = constant-expression , ... }

enum name : type ;

底层类型是实现定义的整数类型,可以表示所有枚举器的值。

The underlying type is an implementation-defined integral type that can represent all enumerator values.

如果枚举器列表为空,底层类型就如同枚举只有一个值为 0 的枚举器。

If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0.

每个枚举器都会成为枚举类型(即名称)的命名常量,在外层作用域中可见,并可在需要常量时使用。

Each enumerator becomes a named constant of the enumeration's type (that is, name), visible in the enclosing scope, and can be used whenever constants are required.

enum Color { red, green, blue };

Color r = red;

switch(r)

{

    case red  : std::cout << "red\n";   break;

    case green: std::cout << "green\n"; break;

    case blue : std::cout << "blue\n";  break;

}

如果第一个枚举器没有 =,则相关值为零。对于定义中没有 = 的其他枚举器,相关值是前一个枚举器的值加一。

If the first enumerator does not have =, the associated value is zero. For any other enumerator whose definition does not have an =, the associated value is the value of the previous enumerator plus one.

enum Foo { a, b, c = 10, d, e = 1, f, g = f + c };

//a = 0, b = 1, c = 10, d = 11, e = 1, f = 2, g = 12

非作用域枚举的名称可以省略:这种声明只是将枚举引入外层作用域:

The name of an unscoped enumeration may be omitted: such declaration only introduces the enumerators into the enclosing scope:

enum { a, b, c = 0, d = a + 2 }; // defines a = 0, b = 1, c = 0, d = 2

Scoped enumerations

enum struct|class name { enumerator = constant-expression , enumerator = constant-expression , ... }

enum struct|class name : type { enumerator = constant-expression , enumerator = constant-expression , ... }

enum struct|class name ;

enum struct|class name : type ;

struct和class两个关键字等效。

第一行和第三行的基础类型(underlying type)都是int。

Using-enum-declaration

using enum nested-name-specifier (optional) name ;(since C++20)

enum class fruit { orange, apple };

struct S

{

    using enum fruit; // OK: introduces orange and apple into S

};

void f(){

    S s;

    s.orange;  // OK: names fruit::orange

    S::orange; // OK: names fruit::orange

}

引入两个同名枚举器的两个 using-enum-declarations 会发生冲突。

Two using-enum-declarations that introduce two enumerators of the same name conflict.

enum class fruit { orange, apple };

enum class color { red, orange };

void f(){

    using enum fruit;    // OK

    // using enum color; // error: color::orange and fruit::orange conflict

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/31376.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

CubeFS - 新一代云原生存储系统

CubeFS 是一种新一代云原生存储系统,支持 S3、HDFS 和 POSIX 等访问协议,支持多副本与纠删码两种存储引擎,为用户提供多租户、 多 AZ 部署以及跨区域复制等多种特性。 官方文档 CubeFS 作为一个云原生的分布式存储平台,提供了多种访问协议,因此其应用场景也非常广泛,下面…

驱动芯片退饱和保护(DESAT)

短路测试和双脉冲测试。 功率模块的短路承受能力的评估分为短路时间评估和短路能量评估两大类。短路时间由短路检测时间与短路关断时间共同构成 短路检测需要兼顾时效性与抗扰性能&#xff0c;要求系统能够及时响应&#xff0c;避免功率模块损坏。同时能够屏蔽开关过程的干扰…

车辆轨迹预测系列 (一):轨迹预测方法综述解析

文章目录 车辆轨迹预测系列 (一)&#xff1a;轨迹预测方法综述解析1、Contextual FactorsPhysics-related factors (物理相关因素):Road-related factors (道路相关因素):Interaction-related factors (交互相关因素): 2、Output TypesUnimodal Trajectory Prediction(单一模式…

AI音乐大模型:是创意的助力还是产业的挑战?

近期音乐界迎来了一场前所未有的革命。随着多家科技公司纷纷推出音乐大模型&#xff0c;素人生产音乐的门槛被前所未有地拉低&#xff0c;一个崭新的“全民音乐时代”似乎已近在眼前。然而&#xff0c;在这场技术革新的浪潮中&#xff0c;关于AI产品版权归属、创意产业如何在AI…

前端深拷贝非常优质的函数,包含函数、循环引用,Set、Map、Date、自定义构造函数等处理

前端深拷贝 前端深拷贝非常优质的函数&#xff0c;包含函数、循环引用&#xff0c;Set、Map、Date、自定义构造函数等处理 function deepClone(obj: any, hash new WeakMap()): any {if (Object(obj) ! obj) return obj // 处理基础类型if (hash.has(obj)) return hash.get(…

Python Web实战:Python+Django+MySQL实现基于Web版的增删改查

项目实战 1.创建项目(sms) File->New Project->Django 稍等片刻&#xff0c;项目的目录结构如下图 项目创建后确认是否已安装Django和mysqlclient解释器&#xff0c;如何确认&#xff1f;file->Settings 如果没有请在Terminal终端输入以下命令完成安装 pip instal…

C++初学者指南第一步---5.介绍std::vector

C初学者指南第一步—5.介绍std::vector 目录 C初学者指南第一步---5.介绍std::vector1.初始化/访问2.添加元素3.Resizing调整大小4.在尾部删除元素5. 复制一直是深拷贝&#xff01; 注意std代表C标准库的命名空间&#xff0c;vector&#xff08;向量&#xff09;是标准库中的一…

18V-180V降5V500mA恒压WT5118

18V-180V降5V500mA恒压WT5118 如何实现18V-180V宽电压输入下的恒压5V 500mA输出。输入电压是波动的18V还是高达180V,WT5118都能确保输出端提供稳定的5V电压和500mA的电流。 WT5118 是一款集成了 180V 高电压 MOSFET 的 DC-DC 控制器&#xff0c;专为开关电源设计。该设备具备内…

数字孪生智慧应用场景——数字孪生智慧城市各行业领域应用场景学习参考资料

下面资源来源于网络&#xff0c;如有侵权请联络删除&#xff01; 数字孪生技术&#xff0c;作为近年来科技领域的热门话题&#xff0c;其发展情况与应用领域正不断拓展深化。简单来说&#xff0c;数字孪生技术是通过构建一个与物理实体相对应的虚拟模型&#xff0c;实现对物理世…

国产化ETL产品必备的特性(非开源包装)

ETL负责将分布的、异构数据源中的数据如关系数据、平面数据文件等抽取到临时中间层后进行抽取、清洗&#xff08;净化&#xff09;、转换、装载、标准、集成&#xff08;汇总&#xff09;...... 最后加载到数据仓库或数据集市中&#xff0c;成为联机分析处理、数据挖掘的基础。…

代码生成器技术乱弹五十三,人工智能和通用代码生成器的共同点:Token

代码生成器技术乱弹五十三&#xff0c;人工智能和通用代码生成器的共同点&#xff1a;Token 现在&#xff0c;随着人工智能的快速发展&#xff0c;特别是生成式人工智能的爆火&#xff0c;大家逐渐熟悉了一个概念&#xff0c;Token。我称之为字牌。在生成式人工智能的语境下&a…

OpenAI 联合创始人 Ilya Sutskever 的新初创公司致力于“安全超级智能”

OpenAI 前首席科学家伊利亚-苏茨克沃尔&#xff08;Ilya Sutskever&#xff09;在今年 5 月离开了他共同创立的人工智能研究公司后&#xff0c;透露了他的下一个重要项目。 相关阅读&#xff1a;GPT-4o通过整合文本、音频和视觉实现人性化的AI交互&#xff0c;OpenAI推出了其新…

大电流与小电流在检测原理上有区别吗

1 常用电流检测原理 1.1 分流器原理 被测量的电流在输入端电阻上Rshunt形成电压正比于测量电流&#xff0c;通过同相比例电路进行放大输出。 缺点&#xff1a; 输入电流减小时&#xff0c;需要更大的Rshunt&#xff1b;输入电阻Rshunt串入检测回路内将引起被测电流减小&a…

山西青年杂志山西青年杂志社山西青年编辑部2024年第10期目录

本刊专稿 共融共创、校企共建BIM创新创业中心的探索与实践 黄强;马福贵;贾晓敏;苏艳贞;魏艳卿; 1-3 财务管理课程专创融合教学改革与实践 宋衍程; 4-7 数字化赋能国际贸易实务课程建设研究 吴珍彩; 8-11《山西青年》投稿&#xff1a;cn7kantougao163.com 青年教育研…

测试时间被压缩的有效应对策略

测试时间被压缩时的有效应对策略 1. 优先级管理2. 使用自动化工具3. 优化测试流程4. 减少测试范围5. 提高测试人员效率6. 快速反馈7. 争取更多有效的资源8. 记录相关风险及建议9. 前期把控10. 测试总结和吸取经验教训 在软件开发中&#xff0c;测试时间的压缩是常见的挑战&…

GD32F303 低功耗模式要点

我们都知道&#xff0c;MCU有低功耗模式&#xff0c;比如GD32F303芯片&#xff0c;就有Sleep、Deepsleep和Standby三种模式。关于这三种模式的具体使用方法&#xff0c;小伙伴们可以参考《GD32F30x系列用户手册》。 今天我们来聊下几个低功耗模式要点。 1、进入低功耗模式后I…

若依RuoYi-Vue分离版—多环境配置

若依RuoYi-Vue分离版—多环境配置 方式一&#xff1a;需要新建application-{profile}.yml文件方式二&#xff1a;不需要新建文件&#xff0c;使用文档分隔符 &#xff08;不推荐&#xff09;总结 若依支持通过简单的配置&#xff0c;切换不同的环境&#xff0c; 如开发环境&…

perfect-scrollbar缩小浏览器窗口滚动条无线滚动的bug

https://github.com/mdbootstrap/perfect-scrollbar/issues/153

Sa-token基本使用教程(全网最详细!!!)

1.概述 1.1 Sa-Token介绍 功能简单示例 1.2 Sa-Token 功能一览 2. 使用 2.1 导入依赖 2.2 springBoot的简单集成 2.2.1 配置文件 2.2.2 controller 2.2.3 简单登录页面 2.3 功能详解 2.3.1 登录认证 2.3.1.1 登录与注销 NotLoginException 登录分析 先校验账号和…

Python3,10行代码,从数据库获取各个维度的数据统计,并把结果输出在Excel中。

10行代码自动统计数据 1、引言2、代码实例3、总结 1、引言 小屌丝&#xff1a;鱼哥帮个忙 小鱼&#xff1a;稍等会哦&#xff0c; 小屌丝&#xff1a;好嘞。 小屌丝&#xff1a; 鱼哥&#xff0c; 还没忙完嘛&#xff1f; 小鱼&#xff1a;快了快了&#xff0c; 再耐心等一等…