繁体   English   中英

C++ 中枚举的具体功能和使用 [暂停]

[英]Specific features and use of enums in C++ [on hold]

除了枚举允许定义常量之间的关系并提高代码可读性这一事实之外,我想在这里讨论这种类型的不同用途。

Indeed, unlike Java for example, C++ enum type is more permissive and behaves like a customizable integer type: its underlying type can be fixed, it does not require specified values, it allows different values than those specified, it is implicitly convertible to int .

优缺点都有什么?

你知道使用的例子吗?

我还发布了我遇到的实际案例的答案

谢谢你。

1. 为自定义 output 格式定义一个 integer 类型

虽然我首先没有找到任何目的,但后来我注意到可以重写 I/O 运算符来为这种类型格式化 output,如下例所示。

#include <iostream>

enum hexa : unsigned int {};

static std::ostream& operator<<(std::ostream &out, const hexa &n) noexcept {
    const std::ios_base::fmtflags &flags = out.flags();
    out << std::hex << std::showbase << std::uppercase << (unsigned int)n;
    out.flags(flags);
    return out;
}

int main(){
    int a = 0x42F05;
    hexa b = (hexa)0x42F05;
    std::cout << a << std::endl;
    std::cout << b << std::endl;
}

Output:

274181
0X42F05

2.定义一个范围integer类型

文档

如果源值 [...] 适合最小的位字段,其大小足以容纳目标枚举的所有枚举数,则它在范围内。 请注意,此类转换后的值可能不一定等于为枚举定义的任何命名枚举数。

因此,可以定义一个类整数类型,它只接受指定范围内的值,如下所示:

#include <iostream>

enum range { min=0, max=31 };

int main(){
    range a = (range)5;
    range b = (range)32;
    std::cout << a << std::endl;
    std::cout << b << std::endl;
}

Output:

test.cpp: In function 'int main()':
test.cpp:8:19: warning: the result of the conversion is unspecified because '32' is outside the range of type 'range' [-Wconversion]
  range b = (range)32;
                   ^~
5
32

3.打印人类可读的值和I18N

这是我最近使用的一个实际案例。 我有一个返回 integer 的方法,它代表星期几,并通过我的代码使用,但我想将它打印为人类可读的值和不同的语言。 感谢枚举,我解决了我的问题。

#include <iostream>

enum dayofweek { monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=7 };

static std::ostream& operator<<(std::ostream &out, const dayofweek &wday) noexcept {
    switch(wday){
    case monday : return out << "Monday";
    case tuesday : return out << "Tuesday";
    case wednesday : return out << "Wednesday";
    case thursday : return out << "Thursday";
    case friday : return out << "Friday";
    case saturday : return out << "Saturday";
    case sunday : return out << "Sunday";
    default : return out << "(N/A)";}
}

/* static int today(){ return 5; } */
static dayofweek today(){ return (dayofweek)5; }

int main(){
    int a = today(); //backward compatibility
    dayofweek b = today();
    std::cout << a << std::endl;
    std::cout << b << std::endl;
}

Output:

5
Friday

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM