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

4.5.1 为什么使用函数

当需要将一部分计算任务独立实现的时候,可以将其定义为一个函数,因为这样可以:

·实现计算逻辑的分离;

·使代码更清晰(通过使用函数名);

·利用函数,使得同样的代码在程序中可以被多次使用;

·减少程序调试的工作量。

在本书的后续内容中,我们将看到很多解释上述原因的示例,并且还会再次谈及某个原因。注意,实际的应用程序可能会用到成百上千个函数,某些程序甚至会用到上百万个函数。显然,如果这些函数不能被清楚地划分和命名的话,任何人都不可能编写和理解这种包含大量函数的程序。而且,你发现很多函数会被重复使用,很快这将导致你厌倦于这种重复性的劳动。例如,编写处理x*x、7*7和(x+7)*(x+7)等的程序可能会令你高兴。但是,对完成同样功能的函数square(x)、square(7)和square(x+7)却可能会让你厌倦。这是因为,求平方是非常容易实现的,但对于复杂函数来说,情况大不相同:对于求平方根函数(C++中的sqrt)来说,程序员更喜欢使用sqrt(x)、sqrt(7)和sqrt(x+7),而不是每一次都重复实现相同的求平方根的代码(这些代码很长、很复杂)。实际上,大多数情况下,你根本不需要了解求解平方根函数的实现细节,而只需要知道sqrt(x)将返回x的平方根就可以了。

在8.5节中,我们将详细介绍相关的函数编写技巧。下面我们将给出另外一个示例。

如果我们想让主函数中的循环更简洁,可将程序改写为:

但我们为什么不用print_square()版本的程序呢?因为这个版本的程序实际上并不比square()版本的程序更简洁。因为: ...

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