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

7.6.3 代码布局

重新检查一下计算器程序,看看其中是否有“丑陋”的代码,我们发现:

在加入对'q'、';'和'%'的处理之前,这段代码还不算太坏,但现在变得有些混乱。代码的可读性越差,其中的错误就越难以发现。而这段代码中确实隐藏着一个潜在的bug!我们修改一下代码,令每行代码只对应switch语句的一种情况,并加入适当的注释来帮助代码理解。修改后的Token_stream的get()函数如下所示:

我们当然可以把对每个数字的处理也放在不同的行,但是那样似乎并不能使代码更加清晰,而且导致不能在一屏上显示get()函数的所有代码。理想情况是,每个函数的代码都能全部显示在屏幕的可视区域上——在屏幕之外我们无法看到的代码是最有可能隐藏bug的地方。因此,代码布局是非常重要的。

另外一个值得注意的地方是,我们在程序中用符号常量quit替代了字符'q'。这不但提高了程序的可读性,而且保证我们的编程错误会被编译器捕获——如果我们为quit操作选择的单词与其他单词冲突,将会产生一个编译时错误。

在代码清理阶段,我们有可能意外地引入一些错误。因此,在代码清理之后一定要测试代码的正确性。最好是每做一点改动就测试一次,以便发现错误时你能记起来是做了什么样的改动导致的这个错误。记住:及早测试,经常测试。 ...

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