gpt4 book ai didi

c++ - 为什么 isocpp 允许我们超过枚举类值?

转载 作者:太空狗 更新时间:2023-10-29 23:43:27 24 4
gpt4 key购买 nike

我在编程时发现了很多有趣的事情,其中​​之一是:

enum class Foo {
FOO_THING,
FOO_TOO
};

int main() {
Foo foo {'d'}; // It is OK
Foo foo2 {3}; // and that one too
}

调试器说它的值为:

foo:  (unknown: 100)
foo2: (Foo::FOO_TOO | unknown: 2)

你能告诉我,为什么允许使用超过声明的枚举类值的值来初始化 Foo 吗?

编译器版本和命令:

Compiler GCC (g++ (Ubuntu 7.3.0-21ubuntu1~16.04) 7.3.0)
$ g++ -Wall -std=c++17 foo.cpp

我真的很想知道在 C++17 中创建该初始化机制的原因?

据我所知,创建枚举类是为了不允许用户以这种方式使用枚举。

最佳答案

Could you tell me, why it is allowed to initialize Foo with values that exceeddeclared enum class values?

正如其他答案之一所说 - 枚举是引擎盖下的整数。哪种整数类型用于特定枚举是特定于实现的。这就是为什么您可以将整数分配给枚举。

As far as I know enum class is created, to not allow users to useenums in that way.

这实际上是不正确的——枚举类的存在是为了无法将枚举TO隐式转换为整数,而不是相反。请注意,将 int 隐式转换为 clas enum 不会造成太多可能的威胁。

请注意,显式强制转换是完全有效的,有时甚至很有用。

作为位标志的枚举

有时枚举可以用作位标志

enum class O{
NOTHING = 0,
VERBOSE = 1,
QUIET = 2,
LOG = 4
};

现在假设您想要传递您的选项,但您希望您的输出被记录下来并且详细。所以你应该通过 4 | 1 = 5。这超过了枚举值。对我来说,只有超过最大值的 class enum 才有效(在某种程度上,这个问题有更好的解决方案)。

关于c++ - 为什么 isocpp 允许我们超过枚举类值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50718897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com