Skip to Content
C++程序设计:原理与实践(基础篇)(原书第2版)
book

C++程序设计:原理与实践(基础篇)(原书第2版)

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
9h 36m
Chinese
Pearson
Content preview from C++程序设计:原理与实践(基础篇)(原书第2版)

9.5.1 “平坦”枚举

使用enum class定义的枚举也被称为是“作用域枚举”(scoped enumeration),除此之外,还有一种称为“平坦”(plain)枚举的定义,和作用域枚举的区别是,平坦枚举将它的枚举量都隐式导出到枚举类型所在的作用域里,并且可以隐式转换到int型。例如:

很明显,平坦枚举没有作用域枚举严格。平坦枚举的枚举量能“污染”枚举类型所在的作用域。有时候这很方便,有时也会导致混乱。例如,当你试图同时使用Month和iostream格式化机制(11.2.1节)时,会发现代表12月(December)的dec和代表十进制(decimal)的dec有冲突。

类似地,允许枚举值转换为int值在使用上会很方便(当我们想转换枚举量到int时无须再显式进行),但有时也会导致诧异。例如:

如果Month是enum class,两个if条件都不会被成功编译。如果monday是平坦枚举量(而不是作用域枚举量),那么month和Monday的比较是允许的,但很可能这会导致意外结果。

我们倾向于使用更简单、更安全的作用域枚举类型,少用平坦枚举类型,但是在旧的代码中有很多平坦枚举量,这是因为enum class是C++11中新出现的功能。

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

C++语言导学(原书第2版)

C++语言导学(原书第2版)

本贾尼 斯特劳斯特鲁普
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano

Publisher Resources

ISBN: 9787111562252