例子:
enum SomeEnum
{
DD,
PP,
NN
};
void someFunc(int a)
{
}
int main()
{
SomeEnum e = DD;
someFunc(a) // calls someFunc with value 0
return 0;
}
这适用于 MSVC,但它是非标准的吗?
谢谢
例子:
enum SomeEnum
{
DD,
PP,
NN
};
void someFunc(int a)
{
}
int main()
{
SomeEnum e = DD;
someFunc(a) // calls someFunc with value 0
return 0;
}
这适用于 MSVC,但它是非标准的吗?
谢谢
Anenum
具有基础整数类型(用于存储 的值的类型enum
),并且该enum
值可以隐式转换为该整数类型的值。
在您的情况下,基础类型为int
,值为 0。一切正常。
It's absolutely valid because, as GManNickG and tomato said, all enums are of type int (in fact, in C, enums ARE ints and you can assign them values outside the scope of the enum.
typedef enum _foo
{
val1 = 57
} foo;
...
foo f = 99; // compiles in C but not C++
In fact, most compilers won't complain if the function argument type was bool or float or some other primitive number type because enums act as constant integer values like 0, -1, 200, etc...
What I'd say though, is that, if you have control over someFunc's signature and you want to ensure in C++ that no invalid values are passed in, change it to be
void someFunc(SomeEnum a);
for more typesafety
Also, always initialize your first enum value at least. I may be wrong on this but, back in the day, the compiler was allowed to pick an arbitrary starting value for your enum. Most of the time it picked 0 but not always. Even if that's not the case, it makes the code a little more self documenting and obvious.
枚举器列表中的标识符被声明为具有 int 类型的常量,并且可以出现在任何允许的地方。
6.7.2.2 这里http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf