Skip to Content
C++语言导学(原书第2版)
book

C++语言导学(原书第2版)

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
5h 35m
Chinese
Pearson
Content preview from C++语言导学(原书第2版)

1.4.2 初始化

在使用对象之前,必须给它赋予一个值。C++提供了多种表达初始化的符号,如前面用到的=,以及一种更通用的形式——花括号限界的初始值列表:

=初始化是一种比较传统的形式,可追溯到C语言,但如果你心存疑虑,那么还是使用通用的{}列表形式。抛开其他不谈,这至少可以令你避免在类型转换中丢失信息:

不幸的是,丢失信息的类型转换,即收缩转换(narrowing conversion),如double转换为int及int转换为char,在C++中是允许的,而且是隐式应用的。隐式收缩转换带来的问题是为了与C语言兼容而付出的代价(参见16.3节)。

我们不可以漏掉常量(参见1.6节)初始化,变量也只有在极其罕见的情况下可以不初始化。也就是说,在引入一个名字时,你应该已经为它准备好了一个合适的值。用户自定义类型(如string、vector、Matrix、Motor_controller和Orc_warrior)可以定义为隐式初始化方式(参见4.2.1节)。

在定义一个变量时,如果它的类型可以由初始值推断得到,则你无须显式指定:

当使用auto时,我们倾向于使用=初始化,因为其中不会涉及带来潜在麻烦的类型转换,但如果你喜欢始终使用{}初始化,也是可以的。

当没有特殊理由需要显式指定数据类型时,一般使用auto。在这里,“特殊理由”包括: ...

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

软件开发实践:项目驱动式的Java开发指南

软件开发实践:项目驱动式的Java开发指南

Raoul-Gabriel Urma, Richard Warburton
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python机器学习案例精解

Python机器学习案例精解

Posts & Telecom Press, Yuxi (Hayden) Liu

Publisher Resources

ISBN: 9787111633280