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.3 默认构造函数

未初始化的变量可能会成为错误之源。为了解决这个问题,我们可以用构造函数来保证类的每个对象都被初始化。例如,我们定义了构造函数Date::Date(int,Month,int)来保证每个Date对象都会被正确地初始化。这意味着程序员必须提供三个类型正确的参数。例如:

注意,虽然我们为Date定义了一个需要三个参数的构造函数,但是通过赋值运算直接拷贝还是没有问题的。

很多类都能很好地理解默认值,也就是说,它们能解决这个问题:“如果我没有为对象提供一个初始值,那么它应该具有什么值?”例如:

这些代码就像注释所描述的那样工作,这看起来很合理。之所以vector和string类能支持这样的特性,是因为它们都有默认构造函数(default constructor),可以隐含地进行所需的初始化工作。

对于类型T,符号T{}表示默认值,这是通过定义默认构造函数实现的,因此,我们可以写出下面这样的代码:

但是,我们更倾向于采用下面这种等价的,但更“口语化”的语法形式:

对于内置类型,如int和double来说,默认构造函数的结果为0,即,int{}是0的一种复杂描述,而double{}是0.0的一种啰嗦的说法。 ...

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