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.3.1 拷贝构造函数

那么,我们应该怎么做呢?答案很明显:提供一个复制元素的拷贝操作,并确保当我们用一个vector初始化另一个vector时,这个拷贝操作会被调用。

一个类的对象的初始化是由该类的构造函数实现的。因此,我们需要一个进行拷贝操作的构造函数。不出意料,这种构造函数被称为拷贝构造函数(copy constructor)。它应接受待拷贝对象的引用作为参数。因此,对类vector,它的拷贝构造函数为如下形式:

我们试图使用一个vector初始化另一个vector时,这一拷贝构造函数就会被调用。拷贝构造函数使用对象引用作为参数的原因在于我们(显然)不希望在传递函数参数时又发生参数的拷贝,而使用const引用的原因在于我们不希望函数对参数进行修改(见8.5.6节)。因此,我们重新定义vector如下:

在从参数vector拷贝元素值之前,拷贝构造函数会设置元素数量(sz),为元素分配内存(初始化elem):

有了这个拷贝构造函数,我们再次考虑之前的例子:

此定义会初始化v2,这是通过调用vector的拷贝构造函数并将v作为参数传递给它而完成的。我们再以三个元素的vector为例,现在v和v2可图示如下: ...

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