#include
using namespace std;
enum class Color { red, green = 20, blue };
int main() {
Color r = Color::blue;
switch (r) {
case Color::red:
std::cout << "红n";
break;
case Color::green:
std::cout << "绿n";
break;
case Color::blue:
std::cout << "蓝n";
break;
}
return 0;
}
#include
using namespace std;
enum class Port : unsigned char; // 前置声明
class MyClass{
public:
void PrintPort(enum class Port p);
};
void MyClass::PrintPort(enum class Port p){
cout << (int)p << endl;
}
int main(){
MyClass a;
a.PrintPort(static_cast(1));
return 0;
}
枚举的大小
每个枚举类型都拥有底层类型,它可以是
显式指定(scoped enum和unscoped enum均可)
省略,该情况下对于有作用域枚举是 int ,或(对于无作用域枚举)是足以表示枚举所有值的实现定义的整数类型
#include
#include
using namespace std;
enum class Color : char { red, blue };
enum class Color2 {
red,
yellow,
green
};
enum Color3 {
red,
yellow,
green
};
enum E {
E1 = 1,
E2 = 2,
Ebig = 0xFFFFFFF0U
};
enum EE : unsigned long {
EE1 = 1,
EE2 = 2,
EEbig = 0xFFFFFFF0U
};
int main() {
constexpr bool e1 = std::is_same_v< std::underlying_type_t, char >;
constexpr bool e2 = std::is_same_v< std::underlying_type_t, int >;
constexpr bool e3 = std::is_same_v< std::underlying_type_t, int >;
constexpr bool e4 = std::is_same_v< std::underlying_type_t, int >;
constexpr bool e5 = std::is_same_v< std::underlying_type_t, unsigned long >;
std::cout
<< " color 底层类型 " << (e1 ? "char" : "non-char") << 'n'
<< " color2 底层类型 " << (e2 ? "int" : "non-int") << 'n'
<< " color3 底层类型 " << (e3 ? "int" : "non-int") << 'n'
<< " E 底层类型 " << (e4 ? "int" : "non-int") << 'n'
<< " EE 底层类型 " << (e5 ? "unsigned long" : "unsigned long") << 'n'
;
return 0;
}
运行结果如下:
color 底层类型 char
color2 底层类型 int
color3 底层类型 non-int
E 底层类型 non-int
EE 底层类型 unsigned long
[1] Enum in C: Understanding The Concept of Enumeration [2] Why is enum class preferred over plain enum? [3] Enumeration declaration [4] enum class – scoped and strongly typed enums [5] Why am I getting this ‘enum’ is not a class or a namespace error? [6] How to use enums in C++ [7] std::pointer_safety