What does enum mean in C++?
In C++, enum is a declaration of an enumeration type. An enumeration type is a collection of integer constants with named values. By using the enum keyword, a new type with predefined values can be created.
Enumeration types can be used to represent a group of related constants, such as days of the week, months, etc. Each enumeration constant has an associated integer value, starting from 0 by default. The names of the enumeration constants can be used instead of their integer values for operations. Below is an example:
enum Weekday {
Monday, // 默认值为0
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
};
int main() {
Weekday today = Tuesday;
if (today == Tuesday) {
// 执行一些操作
}
return 0;
}
In the example above, Weekday is an enumeration type that includes seven enumeration constants. Enumeration constants can be assigned to variables and compared. In this case, the value of today is Tuesday, so the condition is true.
By using enums, code readability can be improved and the problem of using magic numbers can be avoided. Additionally, enum types can also be used for function parameters and return types, making the code more clear and maintainable.