1、C+Primer 中文版(第 4 版)(中英对照)一PrefaceC+ Primer, Fourth Edition, provides a comprehensive introduction to the C+ language. As a primer, it provides a clear tutorial approach to the language, enhanced by numerous examples and other learning aids. Unlike most primers, it also provides a detailed descriptio
2、n of the language, with particular emphasis on current and effective programming techniques.本书全面介绍了 C+ 语言。作为一本入门书( Primer) ,它以教程的形式对 C+ 语言进行清晰的讲解,并辅以丰富的示例和各种学习辅助手段。与大多数入门教程不同,本书对 C+ 语言本身进行了详尽的描述,并特别着重介绍了目前通行的、行之有效的程序设计技巧。Countless programmers have used previous editions of C+ Primer to learn C+. In
3、that time C+ has matured greatly. Over the years, the focus of the languageand of C+ programmershas grown beyond a concentration on run-time efficiency to focus on ways of making programmers more efficient. With the widespread availability of the standard library, it is possible to use and learn C+
4、more effectively than in the past. This revision of the C+ Primer reflects these new possiblities.无数程序员曾使用本书的前几个版本学习 C+,在此期间 C+ 也逐渐发展成熟。这些年来,C+ 语言的发展方向以及 C+ 程序员的关注点,已经从以往注重运行时的效率,转到千方百计地提高程序员的编程效率上。随着标准库的广泛可用,我们现在能够比以往任何时候更高效地学习和使用 C+。本书这一版本充分体现了这一点。Changes to the Fourth Edition第四版的改动In this edition
5、, we have completely reorganized and rewritten the C+ Primer to highlight modern styles of C+ programming. This edition gives center stage to using the standard library while deemphasizing techniques for low-level programming. We introduce the standard library much earlier in the text and have refor
6、mulated the examples to take advantage of library facilities. We have also streamlined and reordered the presentation of language topics.为了体现现代 C+ 编程风格,我们重新组织并重写了本书。书中不再强调低层编程技术,而把中心转向标准库的使用。书中很早就开始介绍标准库,示例也已经重新改写,充分利用了标准库设施。我们也对语言主题叙述的先后次序进行了重新编排,使讲解更加流畅。In addition to restructuring the text, we ha
7、ve incorporated several new elements to enhance the readers understanding. Each chapter concludes with a Chapter Summary and glossary of Defined Terms, which recap the chapters most important points. Readers should use these sections as a personal checklist: If you do not understand a term, restudy
8、the corresponding part of the chapter.除重新组织内容外,为了便于读者理解,我们还增加了几个新的环节。每一章都新增了“小结”和“术语”,概括本章要点。读者可以利用这些部分进行自我检查;如果发现还有不理解的概念,可以重新学习该章中的相关部分。Weve also incorporated a number of other learning aids in the body of the text:书中还加入了下述几种学习辅助手段:Important terms are indicated in bold; important terms that we ass
9、ume are already familiar to the reader are indicated in bold italics. Each term appears in the chapters Defined Terms section.重要术语用黑体表示,我们认为读者已经熟悉的重要术语则用楷体表示。这些术语都会出现在的“术语”部分。Throughout the book, we highlight parts of the text to call attention to important aspects of the language, warn about common
10、 pitfalls, suggest good programming practices, and provide general usage tips. We hope that these notes will help readers more quickly digest important concepts and avoid common pitfalls.书中用特殊版式突出标注的文字,是为了向读者提醒语言的重要特征,警示常见的错误,标明良好的编程实践,列出通用的使用技巧。希望这些标注可以帮助读者更快地消化重要概念,避免犯常见错误。To make it easier to fol
11、low the relationships among features and concepts, we provide extensive forward and backward cross-references.为了更易于理解各种特征或概念间的关系,书中大量使用了前后交叉引用。We have provided sidebar discussions that focus on important concepts and supply additional explanations for topics that programmers new to C+ often find mos
12、t difficult.对于某些重要概念和 C+ 新手最头疼的问题,我们进行了额外的讨论和解释。这部分也以特殊版式标出。Learning any programming language requires writing programs. To that end, the primer provides extensive examples throughout the text. Source code for the extended examples is available on the Web at the following URL:学习任何程序设计语言都需要编写程序。因此,本提
13、供了大量的示例。所有示例的源代码可以从下列网址获得:http:/ hasnt changed from earlier versions is that the book remains a comprehensive tutorial introduction to C+. Our intent is to provide a clear, complete and correct guide to the language. We teach the language by presenting a series of examples, which, in addition to exp
14、laining language features, show how to make the best use of C+. Although knowledge of C (the language on which C+ was originally based) is not assumed, we do assume the reader has programmed in a modern block-structured language.万变不离其宗,本书保持了前几版的特色,仍然是一部全面介绍 C+ 的教程。我们的目标是提供一本清晰、全面、准确的指南性读物。我们通过讲解一系列示
15、例来教授 C+ 语言,示例除了解释语言特征外,还展示了如何善用这门语言。虽然读者不需要事先学过 C 语言( C+ 最初的基础)的知识,但我们假定读者已经掌握了一种现代结构化语言。Structure of This Book本书结构C+ Primer provides an introduction to the International Standard on C+, covering both the language proper and the extensive library that is part of that standard. Much of the power of C
16、+ comes from its support for programming with abstractions. Learning to program effectively in C+ requires more than learning new syntax and semantics. Our focus is on how to use the features of C+ to write programs that are safe, that can be built quickly, and yet offer performance comparable to th
17、e sorts of low-level programs often written in C.本介绍了 C+ 国际标准,既涵盖语言的特征,又讲述了也是标准组成部分的丰富标准库。C+ 的强大很大程度上来自它支持抽象程序设计。要学会用 C+ 高效地编程,只是掌握句法和语义是远远不够的。我们的重点在于,教会读者怎样利用 C+ 的特性,快速地写出安全的而且性能可与 C 语言低层程序相媲美的程序。C+ is a large language and can be daunting to new users. Modern C+ can be thought of as comprising thre
18、e parts:C+ 是一种大型的编程语言,这可能会吓倒一些新手。现代 C+ 可以看成由以下三部分组成:The low-level language, largely inherited from C低级语言,多半继承自 C。More advanced language features that allow us to define our own data types and to organize large-scale programs and systems更高级的语言特征,用户可以借此定义自己的数据类型,组织大规模的程序和系统。The standard library, which
19、 uses these advanced features to provide a set of useful data structures and algorithms标准库,使用上述高级特征提供一整套有用的数据结构和算法。Most texts present C+ in this same order: They start by covering the low-level details and then introduce the the more advanced language features. They explain the standard library only
20、 after having covered the entire language. The result, all too often, is that readers get bogged down in issues of low-level programming or the complexities of writing type definitions and never really understand the power of programming in a more abstract way. Needless to say, readers also often do
21、 not learn enough to build their own abstractions.多数 C+ 教材按照下面的顺序展开:先讲低级细节,再介绍更高级的语言特征;在讲完整个语言后才开始解释标准库。结果往往使读者纠缠于低级的程序设计问题和复杂类型定义的编写等细节,而不能真正领会抽象编程的强大,更不用说学到足够的知识去创建自己的抽象了。In this edition we take a completely different tack. We start by covering the basics of the language and the library together.
22、Doing so allows you, the reader, to write significant programs. Only after a thorough grounding in using the library and writing the kinds of abstract programs that the libary allowsdo we move on to those features of C+ that will enable you to write your own abstractions.本版中我们独辟蹊径。一开始就讲述语言的基础知识和标准库,
23、这样读者就可以写出比较大的有实际意义的程序来。透彻阐释了使用标准库(并且用标准库编写了各种抽象程序)的基础知识之后,我们才进入下一步,学习用 C+ 的其他高级特征来编写自己的抽象。Parts I and II cover the basic language and library facilities. The focus of these parts is to learn how to write C+ programs and how to use the abstractions from the library. Most C+ programmers need to know e
24、ssentially everything covered in this portion of the book.第一和第二部分讨论语言的基础知识和标准库设施。其重点在于学会如何编写 C+ 程序,如何使用标准库提供的抽象设施。大部分 C+ 程序员需要了解本书这两部分的内容。In addition to teaching the basics of C+, the material in Parts I and II serves another important purpose. The library facilities are themselves abstract data typ
25、es written in C+. The library can be defined using the same class-construction features that are available to any C+ programmer. Our experience in teaching C+ is that by first using well-designed abstract types, readers find it easier to understand how to build their own types.除了讲解基础知识以外,这两部分还有另外一个重
26、要的意图。标准库设施本身是用 C+ 编写的抽象数据类型,定义标准库使用的是任何 C+ 程序员都能使用的构造类的语言特征。我们教授 C+ 的经验说明,一开始就使用设计良好的抽象类型,读者会更容易理解如何建立自己的类型。Parts III through V focus on how we can write our own types. Part III introduces the heart of C+: its support for classes. The class mechanism provides the basis for writing our own abstractio
27、ns. Classes are also the foundation for object-oriented and generic programming, which we cover in Part IV. The Primer concludes with Part V, which covers advanced features that are of most use in structuring large, complex systems.第三到第五部分着重讨论如何编写自己的类型。第三部分介绍 C+ 的核心,即对类的支持。类机制提供了编写自定义抽象的基础。类也是第四部分中讨
28、论的面向对象编程和泛型编程的基础。全书正文的最后是第五部分,这一部分讨论了一些高级特征,它们在构建大型复杂系统时最为常用。Acknowledgments致谢As in previous editions of this Primer, wed like to extend our thanks to Bjarne Stroustrup for his tireless work on C+ and for his friendship to these authors throughout most of that time. Wed also like to thank Alex Stepa
29、nov for his original insights that led to the containers and algorithms that form the core of the standard library. Finally, our thanks go to the C+ Standards committee members for their hard work in clarifying, refining, and improving C+ over many years.与前几版一新,我们要感谢 Bjarne Stroustrup,他不知疲倦地从事着 C+ 方
30、面的工作,他与我们的深厚友情由来已久。我们还要感谢 Alex Stepanov,正是他最初凭借敏锐的洞察力创造了容器和算法的概念,这些概念最终形成了标准库的核心。此外,我们要感谢 C+ 标准委员会的所有成员,他们多年来为 C+ 澄清概念、细化标准和改进功能付出了艰苦的努力。We also extend our deep-felt thanks to our reviewers, whose helpful comments on multiple drafts led us to make improvements great and small throughout the book: Pa
31、ul Abrahams, Michael Ball, Mary Dageforde, Paul DuBois, Matt Greenwood, Matthew P. Johnson, Andrew Koenig, Nevin Liber, Bill Locke, Robert Murray, Phil Romanik, Justin Shaw, Victor Shtern, Clovis Tondo, Daveed Vandevoorde, and Steve Vinoski.我们要衷心地感谢本书审稿人,他们审阅了我们的多份书稿,帮助我们对本书进行了无数大大小小的修改。他们是 Paul Abr
32、ahams,Michael Ball,Mary Dageforde,Paul DuBois,Matt Greenwood,Matthew P. Johnson,Andrew Koenig,Nevin Liber,Bill Locke,Robert Murray,Phil Romanik,Justin Shaw,Victor Shtern,Clovis Tondo,Daveed Vandevoorde 和 Steve Vinoski。This book was typeset using LATEX and the many packages that accompany the LATEX d
33、istribution. Our well-justified thanks go to the members of the LATEX community, who have made available such powerful typesetting tools.The examples in this book have been compiled on the GNU and Microsoft compilers. Our thanks to their developers, and to those who have developed all the other C+ c
34、ompilers, thereby making C+ a reality.书中所有示例都已通过 GNU 和微软编译器的编译。感谢他们的开发者和所有开发其他 C+ 编译器的人,是他们使 C+ 变成现实。Finally, we thank the fine folks at Addison-Wesley who have shepherded this edition through the publishing process: Debbie Lafferty, our original editor, who initiated this edition and who had been w
35、ith the Primer from its very first edition; Peter Gordon, our new editor, whose insistence on updating and streamlining the text have, we hope, greatly improved the presentation; Kim Boedigheimer, who keeps us all on schedule; and Tyrrell Albaugh, Jim Markham, Elizabeth Ryan, and John Fuller, who sa
36、w us through the design and production process.最后,感谢 的工作人员,他们引领了这一版的整个出版过程:我们最初的编辑,是他提出出版本书的新版,他从本书最初版本起就一直致力于本书;我们的新编辑,他坚持更新和精简本书内容,极大地改进了这一版本;他保证了我们所有人能按进度工作;还有 、 、和,他们和我们一起经历了整个设计和制作过程。Chapter 1. Getting Started第一章 快速入门CONTENTSSection 1.1 Writing a Simple C+ Program 2Section 1.2 A First Look at I
37、nput/Output 5Section 1.3 A Word About Comments 10Section 1.4 Control Structures 11Section 1.5 Introducing Classes 20Section 1.6 The C+ Program 25Chapter Summary 28Defined Terms 28This chapter introduces most of the basic elements of C+: built-in, library, and class types; variables; expressions; sta
38、tements; and functions. Along the way, well briefly explain how to compile and execute a program.本章介绍 C+ 的大部分基本要素:内置类型、库类型、类类型、变量、表达式、语句和函数。在这一过程中还会简要说明如何编译和运行程序。Having read this chapter and worked through the exercises, the reader should be able to write, compile, and execute simple programs. Subse
39、quent chapters will explain in more detail the topics introduced here.读者读完本章内容并做完练习,就应该可以编写、编译和执行简单的程序。后面的章节会进一步阐明本章所介绍的主题。Learning a new programming language requires writing programs. In this chapter, well write a program to solve a simple problem that represents a common data-processing task: A b
40、ookstore keeps a file of transactions, each of which records the sale of a given book. Each transaction contains an ISBN (International Standard Book Number, a unique identifier assigned to most books published throughout the world), the number of copies sold, and the price at which each copy was so
41、ld. Each transaction looks like要学会一门新的程序语言,必须实际动手编写程序。在这一章,我们将缩写程序解决一个简单的数据处理问题:某书店以文件形式保存其每一笔交易。每一笔交易记录某本书的销售情况,含有 ISBN(国际标准书号,世界上每种图书的唯一标识符) 、销售册数和销售单价。每一笔交易形如:0-201-70353-X 4 24.99where the first element is the ISBN, the second is the number of books sold, and the last is the sales price. Periodi
42、cally the bookstore owner reads this file and computes the number of copies of each title sold, the total revenue from that book, and the average sales price. We want to supply a program do these computations.第一个元素是 ISBN,第二个元素是销售的册数,最后是销售单价。店主定期地查看这个文件,统计每本书的销售册数、总销售收入以及平均售价。我们要编写程序来进行这些计算。Before we
43、 can write this program we need to know some basic features of C+. At a minimum well need to know how to write, compile, and execute a simple program. What must this program do? Although we have not yet designed our solution, we know that the program must在编写这个程序之前,必须知道 C+ 的一些基本特征。至少我们要知道怎么样编写、编译和执行简
44、单的程序。这个程序要做什么呢?虽然还没有设计解决方案,但是我们知道程序必须:Define variables定义变量。Do input and output实现输入和输出。Define a data structure to hold the data were managing定义数据结构来保存要处理的数据。Test whether two records have the same ISBN测试是否两条记录具有相同的 ISBN。Write a loop that will process every record in the transaction file编写循环。处理交易文件中的每一
45、条记录。Well start by reviewing these parts of C+ and then write a solution to our bookstore problem.我们将首先考察 C+ 的这些部分,然后编写书店问题的解决方案。1.1. Writing a Simple C+ Program1.1. 编写简单的 C+ 程序Every C+ program contains one or more functions, one of which must be named main. A function consists of a sequence of state
46、ments that perform the work of the function. The operating system executes a program by calling the function named main. That function executes its constituent statements and returns a value to the operating system.每个 C+ 程序都包含一个或多个函数,而且必须有一个命名为 main。函数由执行函数功能的语句序列组成。操作系统通过调用 main 函数来执行程序,main 函数则执行组
47、成自己的语句并返回一个值给操作系统。Here is a simple version of main does nothing but return a value:下面是一个简单的 main 函数,它不执行任何功能,只是返回一个值:int main()return 0;The operating system uses the value returned by main to determine whether the program succeeded or failed. A return value of 0 indicates success.操作系统通过 main 函数返回的值来
48、确定程序是否成功执行完毕。返回 0 值表明程序程序成功执行完毕。The main function is special in various ways, the most important of which are that the function must exist in every C+ program and it is the (only) function that the operating system explicitly calls.main 函数在很多方面都比较特别,其中最重要的是每个 C+ 程序必须含有 main 函数,且 main 函数是(唯一)被操作系统显式调
49、用的函数。We define main the same way we define other functions. A function definition specifies four elements: the return type, the function name, a (possibly empty) parameter list enclosed in parentheses, and the function body. The main function may have only a restricted set of parameters. As defined here, the parameter list is empty; Section 7.2.6 (p. 243) will cover the other parameters that can be defined for main.定义 main 函数和定义其他函数一样。定义函数必须指定 4 个元素:返回