gpt4 book ai didi

c++ - 关于 C++ 枚举的问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:11:34 25 4
gpt4 key购买 nike

我试过像这样在 for 循环中使用枚举:

enum foo
{
foo_0,
foo_1,
foo_2,
foo_3,
...
foo_n,
foo_count
};

for(foo f = foo_0; f < foo_count; ++f)

我有一个编译错误。我知道这是无效的,因为++f 可能不是有效的 foo 枚举 - 在这种情况下不是,但在一般情况下,所以我将 for 循环切换为:

for(foo f = foo_0; f < foo_count; f = foo(f+1)) 

编译正常。但这引发了以下问题。如果我有 fallowing 语句会怎样?

foo f = foo(k); //k is not a valid foo value

这是未定义的行为吗?

编辑:k 是一个 int,它在 foo 中没有任何对应的值

编辑2:

enum foo
{
foo_0,
foo_1,
foo_2,
foo_3
};

foo f = foo(100); //what value will have f after this according to the standard

感谢您的帮助!

最佳答案

I had a compilation error. I understand that this is not valid because ++f might not be a valid foo enum.

没有。那是对错误的错误解释。它无法编译,因为没有为 foo 类型定义的 operator++

如果将operator++定义为:

foo & operator++(foo & f) 
{
return f = foo(f+1);
}

然后 ++f 会编译并工作:http://ideone.com/1GG09

至于foo(f+1)(或foo(k)),那就没问题了。在内部,foo 是一个整数类型。它的值可以是任何可以由底层整数类型表示的值。

§7.2/6 说,

For an enumeration where emin is the smallest enumerator and emax is the largest, the values of the enumeration are the values of the underlying type in the range bmin to bmax, where bmin and bmax are, respectively, the smallest and largest values of the smallest bit-field that can store emin and emax) It is possible to define an enumeration that has values not defined by any of its enumerators.


编辑:

 foo f = foo(100); //what value will have f after this according to the standard

我认为这里的行为未指定,正如标准在 §7.2/9 中所说的那样,

An expression of arithmetic or enumeration type can be converted to an enumeration type explicitly. The value is unchanged if it is in the range of enumeration values of the enumeration type; otherwise the resulting enumeration value is unspecified.

枚举范围见上引

关于c++ - 关于 C++ 枚举的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7295632/

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