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

5.5.2 被调用者处理错误

在framed_area()内部实现错误检查非常简单,error()仍然可以被用于错误报告:

这一实现非常好,而且我们也不用为每一个frame_area()调用写一个测试。在一个大程序中,对一个会被调用500次的常用函数来说,这一点非常有用。而且,如果需要对错误处理进行修改的话,我们只需要在一处地方进行改动就可以了。

需要注意的是,在这里我们很自然地从“调用者必须检查参数”的方法转变到“函数必须检查自己的参数”的方法(也称为“被调用者检查”)。后者的好处在于参数检查只在一个地方实现。我们不需要在整个程序中查找调用点。而且,参数检查只在这一个地方实现,我们可以方便地掌握参数检查的全部信息。

让我们把这一思想应用于area()中:

上面程序实现了对于area()调用的所有错误处理。因此我们不再需要调用framed_area()。进一步改进,我们可能需要对于错误信息的更准确描述。

函数的参数检查看上去很简单,但是为什么人们不总这么做呢?不注意错误处理是一个原因,粗心大意是另一个原因。此外,还有许多其他因素: ...

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