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.10 前置条件和后置条件

现在,让我们回到前面的问题:如何处理函数的参数错误。基本上,函数调用是思考正确代码和捕捉错误的最佳位置:逻辑上,函数是一个独立计算的开始(函数返回是结束)。看看我们利用前一节介绍的调试技巧做了什么:

首先,我们(在注释中)说明了函数对于参数的要求,然后在函数开始处检查这一要求是否满足(如果不满足则抛出一个异常)。

这是一个很好的基本策略。函数对于自己参数的要求被称为前置条件(precondition):如果函数正确执行的话,这一条件必须为真。现在的问题是如果前置条件被违反的话(为假),那么我们应该怎么做。我们可以有两个选择:

1.忽略它(希望/假设调用者会使用正确的参数)。

2.检查它(并以某种形式报告错误)。

我们可以使用参数类型机制,它能让编译器进行最简单的前置条件检查,并在编译时报告错误。例如:

这里,编译器会检查出“第三个参数应是整型”的函数要求(“前置条件”)被违反了。基本上,我们在本节中要讨论的是如何处理编译器不能检查的函数要求/前置条件。

我们的建议是前置条件一定要在注释里说明(这样调用者可以知道函数的要求)。一个没有注释文档的函数会被认为能够处理每种可能的参数值。但是我们能够确信调用者会读这些注释并遵守其中的规则么?有些时候我们不得不相信调用者会这样做,但我们通常还是要遵循“被调用者进行参数检查”这一原则,它可以解释为“让函数检查自己的前置条件”。在没有其他原因的情况下,我们要坚持做到这一点。不做前置条件检查的常见理由包括: ...

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