C++ - 介绍enum的使用

2024-06-21 14:52
文章标签 c++ 使用 介绍 enum

本文主要是介绍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的使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1081526

相关文章

Python获取C++中返回的char*字段的两种思路

《Python获取C++中返回的char*字段的两种思路》有时候需要获取C++函数中返回来的不定长的char*字符串,本文小编为大家找到了两种解决问题的思路,感兴趣的小伙伴可以跟随小编一起学习一下... 有时候需要获取C++函数中返回来的不定长的char*字符串,目前我找到两种解决问题的思路,具体实现如下:

C++ Sort函数使用场景分析

《C++Sort函数使用场景分析》sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变,如果某些场景需要保持相同元素间的相对顺序,可使... 目录C++ Sort函数详解一、sort函数调用的两种方式二、sort函数使用场景三、sort函数排序

Java String字符串的常用使用方法

《JavaString字符串的常用使用方法》String是JDK提供的一个类,是引用类型,并不是基本的数据类型,String用于字符串操作,在之前学习c语言的时候,对于一些字符串,会初始化字符数组表... 目录一、什么是String二、如何定义一个String1. 用双引号定义2. 通过构造函数定义三、St

Pydantic中Optional 和Union类型的使用

《Pydantic中Optional和Union类型的使用》本文主要介绍了Pydantic中Optional和Union类型的使用,这两者在处理可选字段和多类型字段时尤为重要,文中通过示例代码介绍的... 目录简介Optional 类型Union 类型Optional 和 Union 的组合总结简介Pyd

Vue3使用router,params传参为空问题

《Vue3使用router,params传参为空问题》:本文主要介绍Vue3使用router,params传参为空问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录vue3使用China编程router,params传参为空1.使用query方式传参2.使用 Histo

使用Python自建轻量级的HTTP调试工具

《使用Python自建轻量级的HTTP调试工具》这篇文章主要为大家详细介绍了如何使用Python自建一个轻量级的HTTP调试工具,文中的示例代码讲解详细,感兴趣的小伙伴可以参考一下... 目录一、为什么需要自建工具二、核心功能设计三、技术选型四、分步实现五、进阶优化技巧六、使用示例七、性能对比八、扩展方向建

Java调用C++动态库超详细步骤讲解(附源码)

《Java调用C++动态库超详细步骤讲解(附源码)》C语言因其高效和接近硬件的特性,时常会被用在性能要求较高或者需要直接操作硬件的场合,:本文主要介绍Java调用C++动态库的相关资料,文中通过代... 目录一、直接调用C++库第一步:动态库生成(vs2017+qt5.12.10)第二步:Java调用C++

使用Python实现一键隐藏屏幕并锁定输入

《使用Python实现一键隐藏屏幕并锁定输入》本文主要介绍了使用Python编写一个一键隐藏屏幕并锁定输入的黑科技程序,能够在指定热键触发后立即遮挡屏幕,并禁止一切键盘鼠标输入,这样就再也不用担心自己... 目录1. 概述2. 功能亮点3.代码实现4.使用方法5. 展示效果6. 代码优化与拓展7. 总结1.

使用Python开发一个简单的本地图片服务器

《使用Python开发一个简单的本地图片服务器》本文介绍了如何结合wxPython构建的图形用户界面GUI和Python内建的Web服务器功能,在本地网络中搭建一个私人的,即开即用的网页相册,文中的示... 目录项目目标核心技术栈代码深度解析完整代码工作流程主要功能与优势潜在改进与思考运行结果总结你是否曾经

C/C++错误信息处理的常见方法及函数

《C/C++错误信息处理的常见方法及函数》C/C++是两种广泛使用的编程语言,特别是在系统编程、嵌入式开发以及高性能计算领域,:本文主要介绍C/C++错误信息处理的常见方法及函数,文中通过代码介绍... 目录前言1. errno 和 perror()示例:2. strerror()示例:3. perror(