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

3.5 赋值和初始化

在很多方面,最有趣的运算符是赋值,表示为=。它为一个变量赋予一个新的值。例如:

最后一次赋值需要注意。首先,很明显=并不意味着等于,a不等于a+7。它意味着赋值,也就是将一个新的值赋予一个变量。a=a+7所做的事如下:

1.首先,得到a的值,这里是整数4。

2.接着,将7和4相加,得到整数11。

3.最后,将整数11赋予a。

我们也可以通过字符串来说明赋值:

以上,我们使用“初始化”和“获得新值”来区别两种相似、但是在逻辑上有区别的操作:

·初始化(给一个变量它的初值)。

·赋值(给一个变量一个新的值)。

这些运算是如此相似,因此C++允许我们对它们使用相同的符号(=):

但是,赋值和初始化在逻辑上是不同的。你可以通过类型说明(int或string)来区分它们,它们总是从初始化开始;赋值并不需要这样做。从原则上来说,初始化时变量为空。另一方面,赋值在放入一个新的值之前,首先必须将旧的值清空。你可以将变量看作是一种小的盒子,值是一个可以放入其中的具体东西(例如一枚硬币)。在初始化之前盒子是空的,但是在初始化之后它总是包含一枚硬币,以便在里面放入一枚新的硬币。你(赋值操作符)首先需要移走旧的东西(“销毁旧的值”),你不能使盒子是空的。在计算机内存中并不完全如字面上所说,但是它对于我们理解后面的内容没有坏处。 ...

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