Skip to content

Commit f87ff3f

Browse files
committed
Optimize Article
1 parent 175fb4f commit f87ff3f

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

source/Language Core/Chapter-2/Section-04.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,61 @@ int main() {
289289
}
290290
```
291291
292+
枚举类的优势
293+
294+
强作用域:
295+
296+
枚举值被封装在枚举类内部,不会污染外部作用域
297+
298+
```CPP
299+
enum class Color { Red, Green, Blue };
300+
enum class TrafficLight { Red, Yellow, Green }; // 没问题!
301+
302+
Color c = Color::Red;
303+
TrafficLight t = TrafficLight::Red; // 两者互不冲突
304+
```
305+
306+
强类型(无隐式转换):
307+
308+
枚举类不会隐式转换为 int,必须显式转换
309+
310+
```CPP
311+
enum class Color { Red, Green, Blue };
312+
Color c = Color::Red;
313+
314+
// int num = c; // 错误!不能隐式转换
315+
int num = static_cast<int>(c); // 正确,显式转换为 int(值为 0)
316+
317+
// if (c == 0) { // 错误!不能直接和整数比较
318+
if (c == Color::Red) { // 正确,只能和同类型枚举值比较
319+
// ...
320+
}
321+
```
322+
323+
### 指定底层类型
324+
325+
无论是传统枚举还是枚举类,都可以显式指定底层数据类型(默认是 int)。这在需要控制内存大小或与特定硬件 / 协议交互时很有用
326+
327+
```CPP
328+
// 枚举类指定底层类型为 char(节省空间)
329+
enum class Color : char {
330+
Red,
331+
Green,
332+
Blue
333+
};
334+
335+
// 传统枚举也可以指定底层类型(C++11 起)
336+
enum Status : unsigned int {
337+
OK = 0,
338+
Warning = 1,
339+
Error = 2
340+
};
341+
342+
// 查看枚举大小
343+
std::cout << sizeof(Color) << std::endl; // 输出 1(char 的大小)
344+
std::cout << sizeof(Status) << std::endl; // 输出 4(unsigned int 的大小)
345+
```
346+
292347
## 如何选择
293348

294349
- 能在编译期确定的值 → 使用 constexpr

0 commit comments

Comments
 (0)