当前位置: 首页 > news >正文

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

}

相关文章:

C++ - 介绍enum的使用

在 C 中&#xff0c;枚举关键字用于定义枚举&#xff0c;枚举是一种用户定义的数据类型&#xff0c;由一组命名的积分常量组成。枚举可以用有意义的名称来表示相关常量的集合&#xff0c;从而提高代码的可读性和可维护性。 In C, the enum keyword is used to define an enumer…...

Qt 信号与槽的使用详解 - 多种绑定形式、同步异步、Lambda表达式等

Qt 信号与槽的使用详解 - 多种绑定形式、同步异步、Lambda表达式等 引言一、信号与槽常见的绑定形式二、信号与槽的连接方式 - 同步异步 引言 在Qt框架中&#xff0c;信号与槽&#xff08;Signals and Slots&#xff09;机制是一种强大的通信方式&#xff0c;它允许对象之间进…...

Harbor本地仓库搭建002_Harbor负载均衡节点搭建_nginx安装配置_harbor安装---分布式云原生部署架构搭建002

负载均衡的机器. 可以看到上面是安装nginx的过程 首先去编辑一下yum仓库地址,配置一下nginx的仓库地址 然后这个是配置的内容 然后在进行安装之前最好yum makecache fast 更新一下缓存,这样安装的时候 会安装最新的包 然后就可以安装nginx yum -y install nginx 然后去...

《单元测试之道Java版——使用JUnit》学习笔记汇总

前言 主要用来记录《单元测试之道Java版——使用JUnit》书中的一些必要知识&#xff0c;方便后期编程使用。 目录 序言你的首个单元测试使用Junit编写测试测试哪些内容&#xff1a;Right-BICEPCORRECT边界条件使用Mock对象好的测试所具有的品质在项目中进行测试设计话题 后…...

项目实训-vue(十一)

项目实训-vue&#xff08;十一&#xff09; 文章目录 项目实训-vue&#xff08;十一&#xff09;1.概述2.页顶导航栏3.导航信息4.总结 1.概述 本篇博客将记录我在图片上传页面中的工作。 2.页顶导航栏 <divstyle"display: flex;justify-content: space-between;alig…...

计算机网络-BGP路由负载分担

在大型网络中&#xff0c;到达同一目的地通常会存在多条有效BGP路由&#xff0c;设备只会优选一条最优的BGP路由&#xff0c;将该路由加载到路由表中使用&#xff0c;这一特点往往会造成很多流量负载不均衡的情况。 通过配置BGP负载分担&#xff0c;可以使得设备同时将多条等代…...

Python爬取中国福彩网彩票数据并以图表形式显示

网页分析 首先打开中国福彩网&#xff0c;点击双色球&#xff0c;选择往期开奖栏目 进入栏目后&#xff0c;选定往期的奖金数目作为我们想要爬取的目标内容 明确目标后&#xff0c;开始寻找数据所在的位置 鼠标右击页面&#xff0c;打开网页源代码&#xff0c;在源代码中搜索…...

0621作业

目录 多线程并发服务器模型服务器实现 select的TCP服务器模型服务器实现 select的TCP客户端实现 多线程并发服务器 模型 sfd socket(); bind(); listen(); while(1){newfd accept();pthread_create(&tid, NULL, do_cli_msg, [newfd, cin]集合);pthread_detach(tid); } …...

ps基础入门

1.基础 1.1新建文件 1.2创建指定形状 1.4移动工具 1.41移动画布中的任意元素 1.42移动画布 1.43修改画布大小 1.44修改图像大小 1.5框选工具 1.6矩形工具 1.7图层 1.71图层颜色修改 1.72…...

c语言常用易错记录

c语言常用易错记录 文章目录 c语言常用易错记录1.for循环 1.for循环 示例&#xff1a; #include <stdio.h>int main() {int i;for (i 0; i < 10; i) {printf("%d\n", i);}return 0; }执行顺序 备注&#xff1a;此图来源于b站鹏哥C语言视频课截图&#xf…...

制造业ERP五大生产模式详解!

制造业面临着从成本控制、生产效率到供应链管理的挑战&#xff0c;每一个环节都需要精细化的管理和高效的协同。而ERP系统&#xff0c;作为一种集信息技术与管理思想于一体的管理工具&#xff0c;正逐渐成为制造业转型升级的关键。那么&#xff0c;通过本文你将会了解到&#x…...

​Python20 Numpy基础

NumPy&#xff08;Numerical Python&#xff09;是一个开源的Python库&#xff0c;广泛用于科学计算。它提供了一个高性能的多维数组对象&#xff0c;以及用于处理这些数组的工具和函数。NumPy是数据分析、机器学习、工程和科学研究中不可或缺的工具之一&#xff0c;因为它提供…...

暴雨虐长沙,生灵受煎熬

今天&#xff0c;“湖南长沙市遭遇强降雨,一小时的降雨量足够注满54个西湖”这消息&#xff0c;终于登上互联网社交平台热搜榜。 截图&#xff1a;来源社交网站 综合多家媒体消息概述如下。 昨&#xff08;24日&#xff09;天&#xff0c;湖南长沙市遭遇强降雨&#xff0c;一…...

iptables(5)常用扩展模块iprange、string、time、connlimit、limit

简介 之前我们已经介绍过扩展模块的简单使用,比如使用-m tcp/udp ,-m multiport参数通过--dports,--sports可以设置连续和非连续的端口范围。那么我们如何匹配其他的一些参数呢,比如源地址范围,目的地址范围,时间范围等,这就是我们这篇文章介绍的内容。 iprange扩展模块…...

Mars3d实现汽车尾气粒子效果从汽车屁股开始发射效果

本身的汽车尾气粒子效果&#xff1a;在汽车模型的中间发射的↓↓↓↓↓↓↓↓↓↓↓ Mars3d实例中是使用transY偏移值实现汽车尾气粒子效果从汽车屁股开始发射效果&#xff1a; // 动态运行车辆的尾气粒子效果 function addDemoGraphic4(graphicLayer) {const fixedRoute new…...

01_RISC-V 入门及指令集学习

参考文档 risc-v入门&#xff1a;https://blog.csdn.net/bebebug/article/details/128039038RISC-V OS&#xff1a;https://blog.csdn.net/bebebug/article/details/130551378riscv-spec文档&#xff1a;https://riscv.org/wp-content/uploads/2019/12/riscv-spec-20191213.pd…...

Facebook与地方文化:数字平台的多元表达

在当今数字化时代&#xff0c;社交媒体不仅仅是人们交流的工具&#xff0c;更是促进地方文化传播和表达的重要平台。作为全球最大的社交网络之一&#xff0c;Facebook在连接世界各地用户的同时&#xff0c;也成为了地方文化多元表达的重要舞台。本文将深入探讨Facebook如何通过…...

ArmSoM-Sige7/5/1 和树莓派5规格比较

引言 在当今快速发展的嵌入式系统领域&#xff0c;选择一款性能强大、功能丰富的开发板对于项目的成功至关重要。本文将介绍并比较 Sige7、Sige5、Raspberry Pi 5 和 Sige1 这四款开发板的关键规格和特性&#xff0c;帮助开发者和爱好者选择最适合其需求的平台。 ArmSoM-Sige…...

创建App

自学python如何成为大佬(目录):https://blog.csdn.net/weixin_67859959/article/details/139049996?spm1001.2014.3001.5501 在Django项目中&#xff0c;推荐使用App来完成不同模块的任务&#xff0c;通过执行如下命令可以启用一个应用程序。 python manage.py startapp app…...

2024年6月上半月30篇大语言模型的论文推荐

大语言模型&#xff08;LLMs&#xff09;在近年来取得了快速发展。本文总结了2024年6月上半月发布的一些最重要的LLM论文&#xff0c;可以让你及时了解最新进展。 LLM进展与基准测试 1、WildBench: Benchmarking LLMs with Challenging Tasks from Real Users in the Wild Wi…...

C++实现分布式网络通信框架RPC(3)--rpc调用端

目录 一、前言 二、UserServiceRpc_Stub 三、 CallMethod方法的重写 头文件 实现 四、rpc调用端的调用 实现 五、 google::protobuf::RpcController *controller 头文件 实现 六、总结 一、前言 在前边的文章中&#xff0c;我们已经大致实现了rpc服务端的各项功能代…...

ESP32 I2S音频总线学习笔记(四): INMP441采集音频并实时播放

简介 前面两期文章我们介绍了I2S的读取和写入&#xff0c;一个是通过INMP441麦克风模块采集音频&#xff0c;一个是通过PCM5102A模块播放音频&#xff0c;那如果我们将两者结合起来&#xff0c;将麦克风采集到的音频通过PCM5102A播放&#xff0c;是不是就可以做一个扩音器了呢…...

C++ 求圆面积的程序(Program to find area of a circle)

给定半径r&#xff0c;求圆的面积。圆的面积应精确到小数点后5位。 例子&#xff1a; 输入&#xff1a;r 5 输出&#xff1a;78.53982 解释&#xff1a;由于面积 PI * r * r 3.14159265358979323846 * 5 * 5 78.53982&#xff0c;因为我们只保留小数点后 5 位数字。 输…...

今日科技热点速览

&#x1f525; 今日科技热点速览 &#x1f3ae; 任天堂Switch 2 正式发售 任天堂新一代游戏主机 Switch 2 今日正式上线发售&#xff0c;主打更强图形性能与沉浸式体验&#xff0c;支持多模态交互&#xff0c;受到全球玩家热捧 。 &#x1f916; 人工智能持续突破 DeepSeek-R1&…...

Java求职者面试指南:计算机基础与源码原理深度解析

Java求职者面试指南&#xff1a;计算机基础与源码原理深度解析 第一轮提问&#xff1a;基础概念问题 1. 请解释什么是进程和线程的区别&#xff1f; 面试官&#xff1a;进程是程序的一次执行过程&#xff0c;是系统进行资源分配和调度的基本单位&#xff1b;而线程是进程中的…...

Web中间件--tomcat学习

Web中间件–tomcat Java虚拟机详解 什么是JAVA虚拟机 Java虚拟机是一个抽象的计算机&#xff0c;它可以执行Java字节码。Java虚拟机是Java平台的一部分&#xff0c;Java平台由Java语言、Java API和Java虚拟机组成。Java虚拟机的主要作用是将Java字节码转换为机器代码&#x…...

NPOI Excel用OLE对象的形式插入文件附件以及插入图片

static void Main(string[] args) {XlsWithObjData();Console.WriteLine("输出完成"); }static void XlsWithObjData() {// 创建工作簿和单元格,只有HSSFWorkbook,XSSFWorkbook不可以HSSFWorkbook workbook new HSSFWorkbook();HSSFSheet sheet (HSSFSheet)workboo…...

从物理机到云原生:全面解析计算虚拟化技术的演进与应用

前言&#xff1a;我的虚拟化技术探索之旅 我最早接触"虚拟机"的概念是从Java开始的——JVM&#xff08;Java Virtual Machine&#xff09;让"一次编写&#xff0c;到处运行"成为可能。这个软件层面的虚拟化让我着迷&#xff0c;但直到后来接触VMware和Doc…...

CTF show 数学不及格

拿到题目先查一下壳&#xff0c;看一下信息 发现是一个ELF文件&#xff0c;64位的 ​ 用IDA Pro 64 打开这个文件 ​ 然后点击F5进行伪代码转换 可以看到有五个if判断&#xff0c;第一个argc ! 5这个判断并没有起太大作用&#xff0c;主要是下面四个if判断 ​ 根据题目…...

2025-05-08-deepseek本地化部署

title: 2025-05-08-deepseek 本地化部署 tags: 深度学习 程序开发 2025-05-08-deepseek 本地化部署 参考博客 本地部署 DeepSeek&#xff1a;小白也能轻松搞定&#xff01; 如何给本地部署的 DeepSeek 投喂数据&#xff0c;让他更懂你 [实验目的]&#xff1a;理解系统架构与原…...