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

10.9 用户自定义输入运算符

为一个给定类型和指定的输入格式定义输入运算符<<,关键在于错误处理。这可能会是很棘手的事情。

下面是为9.8节中Date类型定义的一个简单的输入运算符,它要求的输入格式与上一节定义的>>的输出格式相同:

>>运算符读入形如“(2004,8,20)”的数据项,并尝试用这三个整数创建一个Date对象。和前面提到的一样,这里的输入处理要比输出处理难得多。输入比输出更容易出错,实际应用中看也确实如此。

如果未发现“(整数,整数,整数)”格式的输入,>>运算符会令流进入一个非正常状态(fail、eof或bad),并且不会改变目标Date对象的值。成员函数clear()用来设置流的状态。显然,ios_base::failbit将使流进入fail()状态。理想的目标是在输入故障的情况下保持目标Date对象不变,而且这会使代码更干净。对于一个opeartor>>()来说,理想目标是不读取或丢弃任何它未用到的字符,但这太困难了:因为在捕获到一个格式错误之前就已经读入了大量字符。例如,对于输入“(2004,8,30}”,只有当读到最后的“}”时,我们才能判断遇到了一个格式错误,而一般来说,指望退回这么多字符是不可行的。唯一肯定可以保证的是用unget()退回一个字符。如果operator>>()读入一个不合法的Date,如“(2004,8,32)”,Date的构造函数会抛出一个异常,这会使我们跳出operator>>()。

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