Enum type
An enumeration type (enumeration) is a derived data type in C + +, which is a collection of user-defined enumeration constants.
If a variable has only a few possible values, it can be defined as an enumeration (enumeration) type. The so-called "enumeration" refers to the value of the variable is enumerated, the value of the variable can only be listed in the range of values.
To create an enumeration, you need to use the keyword enum. The general form of an enumeration type is:
enum enum -name { List of names }< Span class= "PLN" > var-list Enum-name is the name of the enumeration type. Name list {List of names} is a comma-delimited
Eg1:
enum color { red< Span class= "pun" >, Green, blue } C;//defines an enumeration type named color, and C is an enumeration variable.
< Span class= "pun" >< Span class= "pun" > C = Blue;//assign a value to the enumeration variable C c = Blue
Eg2:
By default, the first name has a value of 0, the second name has a value of 1, the third name has a value of 2, and so on. However, you can also assign a special value to the name, just add an initial value. For example, in the following enumeration, the value of Green is 5.
Enum{ red, green=5,};
Here, the value ofBlue is 6, because by default, each name will be 1 larger than the previous name.
eg
#include <iostream>
using namespace Std;
int main ()
{
Enum School{teacher,student,headmaster} a,b,c;
A=school (0);
B=student;
C=headmaster;
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
cout << "Hello World" << Endl;
return 0;
}
Why use enumerations?
Take a look at this example:
#include<iostream>
using
namespace
std;
void
main()
{
int
per=0;
switch
(per)
{
case
0:
cout<<
"中国人,牛!"
<<endl;
break
;
case
1:
cout<<
"美帝人,黑!"
<<endl;
break
;
case
2:
cout<<
"英国佬,才!"
<<endl;
break
;
default
:
break
;
}
}
//对比
#include<iostream>
using
namespace
std;
enum
Person
{
Chinese,American,English
};
void
main()
{
Person per=American;
switch
(per)
{
case
Chinese:
cout<<
"中国人,牛!"
<<endl;
break
;
case
American:
cout<<
"美帝人,黑!"
<<endl;
break
;
case
English:
cout<<
"英国佬,才!"
<<endl;
break
;
default
:
break
;
}
}
After seeing it, I learned to understand a little, but it felt that way.
Reference: http://www.cnblogs.com/shrimp-can/p/5171110.html
C + + (Analysis of enum type-enum)