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版)

13.4 必要的操作

在学习了前几节的知识之后,我们现在可以讨论如何决定一个类应定义哪些构造函数、是否应定义析构函数、是否应定义拷贝和移动操作这些问题了。有七种必要的操作需要考虑:

·接受一个或多个参数的构造函数。

·默认构造函数。

·拷贝构造函数(拷贝同一类型的对象)。

·拷贝赋值操作(拷贝同一类型的对象)。

·移动构造函数(移动同一类型的对象)。

·移动赋值操作(移动同一类型的对象)。

·析构函数。

通常,我们需要一个或多个构造函数,接受不同参数来初始化对象。例如:

初始化器的含义/用途完全取决于构造函数。标准string的构造函数使用一个字符串作为初始值,而Image的构造函数使用此字符串作为要打开的文件名。通常我们使用构造函数来建立不变式(见9.4.3节)。如果我们无法为类定义一个好的不变式,使得构造函数能建立它的话,那么很可能这个类的设计很糟糕或者它只是一个普通数据结构。

接受参数的构造函数随着所属类的不同而不同,其他操作的形式则更加规则。

我们如何知道一个类是否需要默认构造函数呢?如果我们希望在不指定初始化器的前提下还能构造一个类的对象,那么该类就需要默认构造函数。最常见的例子是我们希望将某个类的对象存放在标准库的vector对象之中。下面的这些代码是正确的,因为int、string和vector<int>都具有默认值:

因此,默认构造函数常常是有用的。问题现在变为:“何时拥有一个默认构造函数是有意义的?”一个答案是:“当我们可以通过一个有意义的、显然的默认值来为类建立起不变式时。”对于值类型,如int和double,显然的默认值为0(对于double,为0.0)。对于string,默认值为空字符串"",这也是显然的。对于vector,默认值为空向量。对于每个类型T,若存在默认值,则T{}为默认值。例如,double{}为0.0,string{}为"",vector<int>()为空的int的vector。 ...

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