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.9.2 不安全转换

安全的转换对程序员通常是一个福音,它可以简化代码编写。不幸的是,C++也允许(隐式的)不安全转换。所谓的不安全,我们的意思是一个值可以转换成一个其他类型的值,这个值不等于原始的值。例如:

这种转换又被称为“窄化”转换,这是由于它们将一个值放入一个对象,这个对象可能太小(“狭窄”)以至于不能存放这个值。不幸的是,只有少数编译器会警告将char初始化为int的不安全。这里的问题是一个int通常比一个char大,因此(在这种情况下)它可以保存一个并不能表示char的int值。尝试执行这个程序,查看你计算机中的值b(常见的结果是32);更进一步,完成实验:

我们使用while语句允许尝试很多值,这个语句将在4.4.2.1节中解释。

试一试

输入各种各样的值来运行这个程序。尝试小的值(例如2和3);尝试大的值(大于127、大于1000);尝试负值;尝试56;尝试89;尝试128;尝试非整型值(例如56.9和56.2)。除了展示在你的机器中如何从double转换成int,以及如何从int转换成char,本程序还显示了对给定整型值,你的机器会输出哪个字符(如果有的话)。 ...

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