在 C++ 中,枚举关键字用于定义枚举,枚举是一种用户定义的数据类型,由一组命名的积分常量组成。枚举可以用有意义的名称来表示相关常量的集合,从而提高代码的可读性和可维护性。
In C++, the enum keyword is used to define an enumeration, which is a user-defined data type consisting of a set of named integral constants. Enumerations are useful for representing a collection of related constants with meaningful names, improving code readability and maintainability.
Basic Enum Definition
Here’s how you can define and use a basic enumeration in C++:
#include <iostream>
// Define an enum outside of any class
enum Color {
RED,
GREEN,
BLUE
};
int main() {
// Declare a variable of type Color
Color myColor = RED;
// Use the enum variable in a switch statement
switch (myColor) {
case RED:
std::cout << "The color is RED" << std::endl;
break;
case GREEN:
std::cout << "The color is GREEN" << std::endl;
break;
case BLUE:
std::cout << "The color is BLUE" << std::endl;
break;
default:
std::cout << "Unknown color" << std::endl;
break;
}
return 0;
}
Scoped Enumerations (enum class)
在 C++11 及更高版本中,可以使用 enum class(或 enum struct)定义作用域枚举。作用域枚举提供了更好的类型安全性,并防止了全局命名空间的污染。
In C++11 and later, you can define scoped enumerations using enum class (or enum struct). Scoped enumerations provide better type safety and prevent pollution of the global namespace.
#include <iostream>
// Define a scoped enum (enum class)
enum class Color {
RED,
GREEN,
BLUE
};
int main() {
// Declare a variable of type Color
Color myColor = Color::RED;
// Use the enum variable in a switch statement
switch (myColor) {
case Color::RED:
std::c