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.7.4 const成员函数

对于有些变量,我们希望它们可以被改变——这也是为什么我们称之为“变量”的原因。但对于另外一些变量,我们则不希望改变它们。即,我们想用“变量”表示的实际上是不变量。我们通常称它们为常量(constant,或者简写为const)。考虑下面代码:

在这里,我们希望d是可变的,start_of_term是不可变的,而some_function()将不被允许对start_of_term进行更改。编译器是如何知道这些的呢?这是因为我们将start_of_term定义为const,从而使编译器获得了上述信息。好了,我们达到了预期的目的,但是,为什么用day()来读取start_of_term的成员day是被允许的呢?实际上,根据前面给出的Date的定义,start_of_term.day()是错误的,因为编译器不知道day()是否修改了对象的日期。我们没有给出过这方面的任何信息,因此编译器应该假定day()有可能改变日期,并报告一个错误。

我们可以将类操作划分为两类——可更改和不可更改,这样就可以解决这个问题了。这个语言特性对于我们深入理解类是非常重要的,而且它也具有很重要的实践意义:不修改对象的操作可以在常量对象上调用。如下例:

在一个成员函数声明中,我们将const放置参数列表右边,就表示这个成员函数可以在一个常量对象上调用。一旦将一个成员函数声明为const,编译器会帮助我们保证这个成员函数不会修改对象。例如: ...

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