C ++ enum, enum

Source: Internet
Author: User

C ++ enum, enum
Why do I need enumeration types?

All the features in programming languages are designed to meet certain needs and to achieve a certain purpose. It will not come out of the box.

Enumeration can be used to save the values of a set of attributes.The full name of. enum is enumeration, which means to list

Looking at this sentence, you may think it is too concise and not easy to understand. let's look at some common examples. in our daily life, we like classification, such as the number, management, and transformation of reading time. what are the levels of government officials? The governor, the mayor, and the county magistrate. the army has the chief, the chief, and the head of the army. in this way, the attribute values of a group are most suitable for Enumeration type representation. when a software application is used, some pages will have many single-choice buttons (radio buttons), which are especially suitable for enumeration to indicate which one you have initiated.

 

In this case, you may not be able to reflect the benefits of enumeration. If not, it indicates that you can only use a group of numbers or strings for the values of some group properties.

Numbers are literally meaningless and have poor readability., So it is rarely used. then we assume that you want to compare strings for many types of judgments, such as if (HisTitle = "stadholder") else if (HistTile = "mayor "). if you think about it for dozens of times, you will know that it is a lot of trouble and a lot of words have completely changed if you try it wrong. It is not easy to find a bug. copying and pasting is always troublesome.Therefore, the string is difficult to edit and error-prone.. If you want to use enumeration, it will be very convenient for us to knock on the Code. The intelligent sensing in the integrated development tool will prompt you and bring it out by hitting a dot. in addition, enumeration will perform type check, and will not be compared by yourself as a string.

 

Memory Allocation for enumeration types

As mentioned above, if there is no enumeration, we generally think of using numbers or strings to represent a category. this is definitely inconvenient to use. maybe you may think of macro representation. for example, # define mayor "mayor" or # define mayor 2

This is naturally a method, but it is not recommended to use Macros in C ++. because C ++ is a strongly typed language, we hope to reduce many errors in the program through the type check, while the macro only performs a simple replacement before the compilation period, bypassing the type check, the advantage of a strong system is lost. second, a group of attribute values are associated information, which must be put together and put in a group.

 

Misunderstanding of constants

Enumeration type members are constants

How can this sentence be understood? That is, enum MyEnum {one = 1, two, three };

Similar to const int one = 1; const int two = 2; const int three = 3.

 

Speaking of constants, there is actually a very misleading place, because we can use macro # define to define constants. Here we only involve simple replacement, and there is naturally no memory allocation problem. however, a constant is also called a constant defined by const, while a constant defined by const seems to have only multiple const keywords. you may assume that constants are simply replaced, so there is no memory allocation. so according to this logic, isn't it a constant defined by const, and there is no memory allocation for enumeration types?

This is true most of the time, but it is not always the case. In some cases, you need to allocate memory.

 

1. No need to allocate memory

If the constant const int one = 1 is defined, and one is assigned to other variables as the right value, there is no memory allocation. however, the constants here are different from the constants defined by # define. The constants defined by the macro are simply replaced before compilation, and no type check is required. the const-defined constants will be checked for the type during compilation and replaced after compilation. after compilation, the const information is invisible and converted to the corresponding value. the information defined by const is only saved in the symbol table.

Similarly, if only enum MyEnum {one = 1, two, three}; defines an enumeration type, and then simply assigns the right value to other variables. for example, int num = MyEnum: one; it only saves the information in the symbol table and is replaced after compilation.

Some people may say that if sizeof MyEnum is used, it will be 4 (in VS, different compilers may be different). Therefore, no matter how many elements in the enumeration are allocated, the memory is 4. this does not actually mean that memory will be allocated when an enumeration variable of the MyEnum type is defined. this is the same as defining a class. You can see the size when you test it with sizeof, but we know that the memory is actually allocated only after the class is instantiated.

 

2. Memory Allocation

1) const int one; is a member variable of the Class 2.) extern const int one = 123; 3.) const int one = 1; int * pConst = & one;

In the above three cases, the memory needs to be allocated.

The enumerated type defines an enumerated type variable instead of simply assigning values to other variables.

For example, MyEnum grade = MyEnum: one; // a 4-byte memory is allocated. (But it is said that the compiler will optimize it. If all values of the enumeration type are expressed in two bytes, the actual allocation will only be two bytes. not necessarily the length of the default int type)

 

Enumeration type usage

Generally, an enumeration type is defined in a global domain. For example

Enum MyEnum {one, two, three}

If this parameter is not explicitly specified, the first value is assigned 0 by default, and then the value is incremented by 1. If a value is explicitly specified, the next value is 1.

In the preceding example, one = 0; two = 1; three = 2;

If you explicitly specify enum MyEnum {one, two = 3, three}

One = 0; two = 3; three = 4;

 

Define an enumeration type MyEnum grade = MyEnum: one;

 

Which is not commonly used.

After declaring an enumeration in the class, you can define the enumeration type to save the prefix of the field. for example, MyEnum my = one; in the same scope, the name of a variable cannot be the same as that of the element in the enumeration, that is, other variables cannot be named on, two, three.

In addition, enumeration is rarely used.

Enum {one, two, three}; that is, no name is specified, So we naturally cannot define some enumeration types. in this case, it is equivalent to const int one = 0; in this way, the three constants are defined as the same.

Then int no = one;

 

A negative number can be assigned during initialization, and the subsequent identifiers will be incremented by 1;


X = 2;
Yes, it is not allowed. If X is assigned a value, type conversion can only be performed on 3. That is:
X = (string) 2;
That's right.
If x is not assigned an integer number, it is a linear number, for example:
X = (string) 'A ';
At this time, the value of x is not the character 'a', but the ASCII code of 'A'. We know that in the enumeration type, the values of constants can only be integer, therefore, the 'A is automatically converted into an integer in the previous meeting. from the memory perspective, in fact, the shaping and balanced variables in C/C ++ are the same, and they can be converted to each other.

 

For example
Namespace
{
Enum B {b1, b2 };
Class C
{
};
}

Here we think B is a type. In terms of type, we can understand that enmu and class, struct are equal, so we can safely define it.
A: B = A: b1;

Note that the value assignment on the right is essentially defined in namespace A as A public const of.
Sometimes it is unreasonable to define too many enmu directly in the namespace, which will pollute the namespace. Therefore, we should define the enmu variable inside the class as much as possible.

Similarly, the default value of enum is required. Enmu always starts from 0. If we do not specify the default value, The enum of the two namespaces in the same namespace will start from 0. In most cases, this will not cause problems, but in order to prevent them from happening, we try
1. Define enum in a proper namespace
2. Specify the default value for enum

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.