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.6 运算符重载

你可以在类或枚举对象上定义几乎所有C++运算符,这通常称为运算符重载(operator overloading)。这种机制用于为用户自定义类型提供习惯的符号表示方法。如下例:

其中:是“算术if”运算符:当(m==Dec)时m的值变为Jan,否则m的值为Month(int(m)+1)。这是对十二月后继月份“绕回”一月这一特性的一种非常简洁的描述方法。现在,我们可以像如下代码一样使用Month类型:

你可能觉得增加Month对象值这样的操作没那么常用,不至于设计一个专门的运算符。可能确实是这样,那么输出运算符又如何呢?如下代码定义了一个输出运算符:

这里假定month_tbl已经在其他位置进行了初始化,每个数组元素保存了对应月份的恰当的名字,如month_tbl[int(Month::mar)]的值为字符串“March”或其他合适的名字;参见10.11.3节。

你可以为自己的类型重新定义几乎所有的C++运算符,如+、-、*、/、%、[]、()、^、!、&、<、<=、>、>=等等。不能定义新的运算符,你可能想在程序中把**或$=作为运算符,但C++不允许你这样做。而且,重载运算符时,运算对象数目也必须与原来一样。例如,你可以定义一元运算符-,但不能定义一元的<=(小于等于),你可以定义二元运算符+,但不能定义二元的!(非)。原则上,C++允许你对自定义类型使用已有的语法,但不允许扩展语法。 ...

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