简体   繁体   English

C ++中的Typedef枚举

[英]Typedef enum in C++

I have one typedef like this 我有一个这样的typedef

typedef enum
{
ONE = 01,
TWO = 02,
THREE = 03
}number_t;

I just defined one member variable as number_t m_number; 我只是将一个成员变量定义为number_t m_number;

so if I return m_number in any other functions what will be returned either ONE or TWO or THREE ? 因此,如果我在其他任何函数中返回m_number,将返回一个还是两个或三个?

Since you didn't initialise the variable, it has an indeterminate value . 由于您没有初始化变量,因此它具有不确定的值

Thus it could be one of the integers that maps to ONE , TWO or THREE , or any other value. 因此,它可以是映射到ONETWOTHREE或其他任何值的整数之一。

It's not, in itself, wrong for an enum object to have a value that doesn't map to the enumerator, so that isn't a big problem. enum对象具有不映射到枚举器的值本身并不是错误的,所以这不是一个大问题。 However, you cannot legally evaluate an indeterminate value, so you won't be able to safely observe this object until you assign it a value. 但是,您不能合法地评估不确定的值,因此,在为它分配值之前,您将无法安全地观察该对象。

As an aside, you're in for a shock when you get to 08 , and even more so if you skip to 010 . 顺便说一句,当您到达08时,您会感到震惊,如果跳至010 ,您将感到震惊。 Don't use leading zeroes on integer literals unless you really intend to count in octal. 除非您真的打算算八进制数,否则不要在整数文字上使用前导零。

Here's what you ought to do: 这是您应该做的:

enum number_t
{
   ONE   = 1,
   TWO   = 2,
   THREE = 3
};

number_t number = ONE;

Just like any other local variable, if it isn't initialized by your code then the content will be whatever is on the stack and in this case completely random. 就像任何其他局部变量一样,如果未通过代码初始化它,则内容将是堆栈中的任何内容,在这种情况下,它将是完全随机的。

If you want to be sure what the value is going to be then intialise it before use, add to your enum something like: 如果您想确定该值是什么,然后在使用前将其初始化,请向您的枚举添加如下内容:

NUMBER_NOT_SET = 0

Then on entry to your function: 然后在进入函数时:

number_t m_number = NUMBER_NOT_SET; number_t m_number = NUM​​BER_NOT_SET;

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

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