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 枚举类型

枚举(enumeration,简写为enum)是一种非常简单的用户自定义类型,它指定一个值的集合,这些值用符号常量表示,称为枚举量(enumerator)。下面是一个例子:

一个枚举定义的“体”就是一个简单的枚举量列表。enum class中的class表示枚举量在枚举作用域内,也就是说,必须用Month::jan来表示jan。

你可以为枚举量指定特定的值,就像上面代码为jan指定值一样。也可以不指定,让编译器选择合适的值。如果让编译器来选择值,它赋予每个枚举量的值为上一个枚举量的值加上1。因此,上面Month的定义赋予月份从1开始的连续整数。此定义与下面的定义是等价的:

但是,第二种定义一方面冗长乏味,另一方面容易出错。实际上,我们在输入第二个定义时出现了两个错误,经过修改后才得到上面的正确版本。因此,最好还是让编译器来做这种简单的、重复性的“机械性”工作。编译器比我们更擅长这种工作,而且它不会厌烦。

如果我们不初始化第一个枚举量,那么编译器会从0开始计数。例如:

这里monday==0,而sunday==6。在实践中,从0开始往往是一种好的选择。

我们可以像下面代码那样使用Month:

注意,Month是一个独立的类型,与“构成其基础”的int型不同。每个Month值都对应一个相等的整型值,但很多整型值没有相等的Month值。例如,我们肯定希望下面的初始化失败: ...

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