C++: Enumeration type



1. Enumeration type

In some cases, the value of the data has only limited possibilities. For example, there are only 4 situations in which a game is won, lost, tied, and the game is cancelled, and there are only 7 days a week. Although int and char types can be used to represent them, it is a troublesome thing to check the legality of the data. So, is there a data type that has only a limited number of values ​​and can automatically check the validity of the data? The answer is yes. The enumeration type in C++ is specifically used to solve such problems.

grammar:

enum enumeration type name {list of variable values};

E.g:

enum Weekday {SUN, MON, TUE, WED, THU, FRI, SAT};

Application description of enumeration type:

  1. The enumeration elements are treated as constants, and values ​​cannot be assigned to them. For example, the following statement is illegal:
    SUN = 0; // SUN is an enumeration element, this statement is illegal
  2. Enumeration types have default values, they are in order: 0, 1, 2, .... For example, in the above example, the value of SUN is 0, MON is 1, TUE is 2,..., SAT is 6.
  3. You can also define the value of the enumeration element separately during the declaration, such as:
    // Define SUN as 7, MON as 1, and then add 1 in order, and SAT as 6.
    enum Weekday {SUN = 7, MON = 1, TUE, WED, THU, FRI, SAT};
  4. Enumeration types can perform relational operations.
  5. Integer values ​​cannot be directly assigned to enumerated variables. If you need to assign integers to enumerated variables, you should perform a forced type conversion.

2. An example

#include <iostream>
using namespace std;

enum GameResult
{
    
    
	WIN,
	LOSE,
	TIE,
	CANCEL
};

int main(int argc, char* argv[])
{
    
    
	GameResult result; // 声明变量时,可以不写关键字 enum
	enum GameResult omit = CANCEL; // 也可以在类型前面写 enum

	for (int count = WIN; count <= CANCEL; count++) // 隐含类型转换
	{
    
    
		result = GameResult(count); // 显式类型转换
		if (result == omit)
		{
    
    
			cout << "The game was canceled." << endl;
		}
		else
		{
    
    
			cout << "The game was played";
			if (result == WIN)
			{
    
    
				cout << " and we won!";
			}
			else if (result == LOSE)
			{
    
    
				cout << " and we lost.";
			}
			else
			{
    
    
				cout << ".";
			}
			cout << endl;
		}
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/PursueLuo/article/details/104456792