阅 读 说 明 您现在所阅读的这本电子图书由“E类出版物”制作出 品。本书版权归作者所有,“E类出版物”只负责制作发行 工作。 在保证原书内容完整的情况下,您可以对本书进行转载 。如果您愿意,我们很乐意您在转载的时候写上我们网站的 名字。 如果您需要使用本书中的部分或者全部内容用于某种商 业用途,请联系作者,在征得原作者同意的情况下您可以继 续您的行为。但如果您没有征得作者同意而擅自用于某种商 业目的,“E类出版物”将不对此负任何责任。 如果您有意出版您的作品,或者您有制作好的别人的作 品,我们都欢迎您授权我们为您制作或者出版,联系信箱是 :[email protected]。 欢迎您订阅我们的更新电子杂志!如果您不经常上网, 但又担心错过“E类出版物”更新的内容,您可以在您方便 的时候登录我们的网站,在首页上您会看到“更新邮件”一 项,您可以使用一个安全的E-mail 地址来订阅。今后每次 更新我们都会通过电子邮件的方式发送给您。 如果您有任何疑问,请跟“E类出版物”站长联系。 网站地址:http://www.epubcn.com 论坛地址:http://www.epubcn.net 联系信箱:[email protected] C++ Primer 3rd Edition – e类出版物 [http://www.epubcn.com] 制作出品 C++ Primer Third Edition Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Addison-Wesley was aware of a trademark claim, the designations have been printed in initial capital letters or all capital letters. The authors and publisher have taken care in preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. The programs and applications presented in this book have been included for their instructional value. They have been tested with care, but are not guaranteed for any particular purpose. The authors and publisher do not offer any warranties or representations, nor do they accept any liabilities with respect to the programs or applications. The publisher offers discounts on this book when ordered in quantity for special sales. For more information please contact: Corporate, Government, and Special Sales Addison Wesley Longman, Inc. One Jacob Way Reading, Massachusetts 01867 Copyright Information Copyright © 1998 by AT&T, Objectwrite, Inc., and Josée Lajoie Library of Congress Cataloging-in-Publication Data Lippman, Stanley B. C++ Primer / Stanley B. Lippman, Josée Lajoie.— 3rd ed. p. cm. Includes bibliographical references and index. ISBN 0-201-82470-1 1. C++ (Computer program language) I. Lajoie, Josée. II. Title . QA76.73.C15L57 1998 - 1 - C++ Primer 3rd Edition – e类出版物 [http://www.epubcn.com] 制作出品 005. 13'3—dc21 98-9464 CIP All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. Published simultaneously in Canada. Cover photograph © 1997 Barbara Hricko Wait 3 4 5 6 7 8 9--CRS--0302010099 Third printing, June 1999 To Beth, who makes this, and all things, possible To Daniel and Anna, who contain virtually all possibilities - SBL To Mark and Mom, for their unconditional love and support. - JL Preface Quite a few changes have occurred between the second and third editions of C++ Primer. Most notably, C++ has undergone international standardization, which has not only added new features to the language, such as exception handling, run-time type identification, namespaces, a built-in Boolean data type, and a new cast notation, but has also extensively modified and extended existing features, such as templates, the class mechanism in support of both object-oriented and object-based programming, nested types, and overload function resolution. Perhaps of even more significance, an extensive library is now part of Standard C++, including what was previously referred to as the Standard Template Library, or STL. A new string type, a set of sequence and associative container types — such as vector, list, map, and set — and an extensible collection of generic algorithms to operate on those types are all features of this new standard library. There's not only quite a lot of new material to cover but also new ways to think about how we program in C++. In short, not only has C++ been, in effect, newly invented, but so has the C++ Primer for this, its third edition. - 2 - C++ Primer 3rd Edition – e类出版物 [http://www.epubcn.com] 制作出品 Not only has the treatment of the language changed fundamentally in this third edition, but so has the authorship: in the first place, we've doubled ourselves! Moreover, we've internationalized in the process, although we're firmly rooted in the North American continent: Stan is American; Josée is Canadian. Finally, the twin authorship reflects the twin primary activities of the C++ community: Stan is currently involved in the efficient workplace application of C++ at Walt Disney Feature Animation for 3D computer graphics and animation, while Josée is involved in the definition and implementation of C++, both as chair of the Core Language subcommittee of the standards effort and as a member of the C++ compiler team at the IBM Canada Laboratory. Stan was one of the original members of the Bell Laboratories team working with Bjarne Stroustrup, the inventor of C++, and has been involved with C++ since 1984. Stan worked on the various implementations of cfront, the original C++ implementation, from Release 1.1 in 1986 through Release 3.0, leading the development team for the 2.1 and 3.0 releases. After that, he worked under Stroustrup on what was known as the Foundation Research Project on the Object Model component of a programming development environment. Josée has been a member of the C++ compiler team at the IBM Canada Laboratory for eight years. She has been a member of the Standards committee since 1990. She was vice-chair of the committee for three years and has been the chair of the Core Language subcommittee for four years. C++ Primer, Third Edition, represents an extensive revision of the text to reflect not only the changes and extensions to the language but also changes to the authors' insights and experience. Structure of This Book C++ Primer provides a comprehensive introduction to the International Standard on C++. It is a primer in the sense that it provides a consciously tutorial approach to describing the C++ language. (It is not a primer in the sense of providing a simplistic or "gentle" description of the language.) Programming aspects of the language, such as exception handling, the container types, object-oriented programming, and so on, are presented in the context of solving a particular problem or programming task. Language rules, such as the resolution of an overloaded function call or the type conversions supported under object-oriented programming, are given extensive treatment that may initially seem out of place in a primer. We believe that the coverage is necessary to a practical understanding of the language, and we view the material as something one goes back to rather than digests at one sitting. If you find it initially overwhelming or simply too dry, put this material aside until later — we identify such sections with the following convention: - 3 - C++ Primer 3rd Edition – e类出版物 [http://www.epubcn.com] 制作出品 Knowledge of the C language is not assumed, although familiarity with some modern, block structured language will make the going easier. The book is intended as a first book on C++; it is not intended as a first book on programming! To be sure, we all start with a common vocabulary; however, the initial chapters cover some basic concepts, such as looping statements and variables, that some readers might find too introductory. Not to worry: the depth of coverage picks up quickly. Much of the power of C++ comes from its support for new ways of programming and thinking about programming problems. Learning to use C++ effectively, therefore, requires more than simply learning a new set of syntax and semantics. To facilitate this larger learning, the book is organized around a series of extended examples. These examples are used both to introduce the details of various language features and to motivate them. When we learn language features in the context of a full example, it becomes clear why such features are useful, providing a sense of when and how we would use them for real-world problem solving. Additionally, this focus on examples allows early use of concepts that will be explained more fully as the reader's knowledge base is built up. Early examples contain simple uses of fundamental C++ concepts, giving a flavor for the kinds of programming one can do in C++ without requiring complete understanding of the details of design and implementation. Chapters 1 and 2 form a self-contained introduction and overview to the entire C++ language. Part I is intended to get us up to speed on the concepts and language facilities supported by C++ — and the fundamentals on writing and executing a program. Upon finishing this part of the text, you should have a feel for the language support C++ provides and a sense of not really understanding it at all. That's ok: that's what the rest of the text is for! Chapter 1 introduces us to the basic elements of the language: the built-in data types, variables, expressions, statements, and functions. It looks at a minimum legal C++ program, briefly discusses the process of compiling our programs, walks through what is spoken of as the preprocessor, and takes a first look at support for input and output. It presents a number of simple but complete C++ programs that the reader is encouraged to compile and execute. Chapter 2 introduces the support C++ provides for object-based and object-oriented programming through the class mechanism, illustrating both through the evolution of an array abstraction. In addition, it briefly introduces templates, namespaces, exception handling, and the standard library support for general container types and generic programming. This chapter is rather fast-paced, and some readers may find it somewhat overwhelming. If that is the case, we suggest you skim through it and return to it later. Fundamental to C++ are the various facilities that allow the user to extend the language itself by defining new data types that then can be used with the - 4 - C++ Primer 3rd Edition – e类出版物 [http://www.epubcn.com] 制作出品 flexibility and simplicity of the built-in data types. The first step to mastery is to understand the base language itself. Chapters 3, 4, 5, 6 (Part II) introduce the language at this level. Chapter 3 introduces the built-in and compound data types predefined by the language together with the string, complex, and vector class data types provided by the C++ standard library. These types form the basic building blocks of all our programs. Chapter 4 provides a detailed discussion of the expressions supported by the language, such as the arithmetic, relational, and assignment expressions. Statements, which form the smallest independent unit within a C++ program, are the topic of Chapter 5. The container types provided by the standard C++ library are the focus of Chapter 6. Rather than provide a simple listing of the available operations, we have walked through the implementation of a text query system to illustrate their design and use. Chapters 7, 8, 9, 10, 11, 12 (Part III) focus on the procedural-based programming support provided by C++. Chapter 7 introduces the C++ function mechanism. Functions encapsulate a set of operations that generally form a single task, such as print(). (The empty parentheses following a name indicate that it represents a function.) The notions of program scope and lifetime of variables, together with a discussion of the namespace facility, are the topics of Chapter 8. Chapter 9 extends the discussion of functions introduced in Chapter 7 to introduce function overloading. Function overloading allows multiple function instances that provide a common operation (but require differing implementations) to share a common name. For example, we can define a collection of print() functions to output different types of data. Chapter 10 introduces and illustrates the use of function templates. A function template provides a prescription for the automatic generation of a potentially infinite set of function instances varying by type but whose implementations remain invariant. C++ supports an exception handling facility. An exception represents unexpected program behavior, such as the exhaustion of all available program memory. The portion of the program within which the exception occurs throws an exception — that is, makes it available to the rest of the program. Some function within the program must then catch the exception and do whatever is necessary. The treatment of exception handling is split across two chapters. In Chapter 11, the basic syntax and use of exception handling are introduced using a simple example of catching and throwing an exception of class type. Because the actual exceptions handled in our programs are usually class objects of an object-oriented class hierarchy, the discussion of how to throw and handle exceptions continues in Chapter 19, after the introduction of object-oriented programming. - 5 - C++ Primer 3rd Edition – e类出版物 [http://www.epubcn.com] 制作出品 Chapter 12 introduces the extensive collection of generic algorithms provided by the standard library and examines how they interact with the container types of Chapter 6 as well as with the built-in array type. The chapter begins by walking through a program design using the generic algorithms. Iterators, introduced in Chapter 6, are discussed further in Chapter 12 because they provide the glue that binds the generic algorithms to the actual containers. The concept of a function object is also introduced and illustrated. Function objects allow us to provide alternative semantics for operators used with the generic algorithms, such as the equality or the less-than operator. The algorithms themselves are detailed, with an illustration of their use, in the Appendix. Chapters 13, 14, 15, 16 (Part IV) focus on object-based programming — that is, the definition and use of the class facility to create independent abstract data types. By creating new types to describe the problem domain, C++ allows the programmer to write applications with much less concern for the various bookkeeping aspects that make programming tedious. The types fundamental to the application can be implemented once and reused, allowing the programmer to concentrate on the problem rather than the details of the implementation. Facilities for encapsulating the data can dramatically simplify subsequent maintenance and evolution of our applications. Chapter 13 focuses on the general class mechanism: how to define a class, the concept of information hiding — that is, of separating the public class interface from the private implementation — and how to define and manipulate object instances of a class, as well as a discussion of class scope, nested classes, and classes as namespace members. Chapter 14 details the special support C++ provides for the initialization, destruction, and assignment of class objects using special member functions spoken of, respectively, as a constructor, destructor, and copy assignment operator. We also look at the issue of memberwise initialization and copy, in which one class object is initialized or assigned with another object of its class, and the special named return value optimization for the efficient support of memberwise initialization and copy. Chapter 15 looks at class-specific operator overloading, first presenting general concepts and design considerations and then looking at specific operators, such as the assignment, subscript, call, and class-specific new and delete operators. The notion of a friend to a class with special access permission and why friends are sometimes needed is also presented. User-defined conversions are then discussed, including the underlying concepts and an extensive example of their use. The rules for function overload resolution are also discussed in this chapter in some detail, with extensive illustration by code examples. - 6 - C++ Primer 3rd Edition – e类出版物 [http://www.epubcn.com] 制作出品 Class templates are the topic of Chapter 16. A class template is a prescription for creating a class in which one or more types or values are parameterized. A vector class, for example, may parameterize the type of element it contains. A buffer class may parameterize not only the type of element it holds but also the size of its buffer. In a more sophisticated usage, such as in distributed computing, the IPC interface, addressing interface, and synchronization interface might all be parameterized. This chapter includes discussions on how to define a class template, how to create specific type instances of a class template, how to define the members of a class template (member functions, static members, and nested types), and how to organize our programs using class templates. It concludes with an extended class template example. Object-oriented programming and the facilities in C++ that support it are the topic of Chapters 17, 18, 19, and 20 (Part IV). Chapter 17 introduces the C++ facilities that support the primary elements of object-oriented programming: inheritance and dynamic binding. In object-oriented programming, parent/child relationships (spoken of as type/subtype relationships) are defined between classes that share common behavior. Rather than reimplement shared characteristics, a class inherits the data and operations of its parent class. The child class, or subtype, programs only its differences with its parent class. For example, we may define a parent Employee class type and two children: TemporaryEmpl and Manager. These subtypes inherit all the behavior of an Employee. They implement the behavior that is unique to each of their respective types. A second aspect of inheritance, spoken of as polymorphism, is the ability of a parent type to refer to any of the subtypes that are inherited from it. An Employee, for example, can address its own type or that of TemporaryEmpl or Manager. Dynamic binding is the ability to resolve at run-time which operation to execute based on the actual type of the polymorphic object. In C++, this is handled through the virtual function mechanism. Chapter 17 introduces the basic features of object-oriented programming. It walks through the design and implementation of a Query class hierarchy in support of the text query system we began implementing in Chapter 6. Chapter 18 introduces the more-complicated inheritance hierarchies that are made possible through multiple and virtual inheritance. It extends the template class example of Chapter 16 into a three-level class template hierarchy using multiple and virtual inheritance. Chapter 19 introduces the run-time type identification (RTTI) facility. RTTI allows our programs to query a polymorphic class object as to its type during execution of the program. For example, we can ask an Employee object whether it actually addresses a Manager type. In addition, Chapter 19 revisits exception - 7 - C++ Primer 3rd Edition – e类出版物 [http://www.epubcn.com] 制作出品 handling to discuss the standard library exception class hierarchy and illustrate defining and handling our own exception class hierarchies. It also provides an in-depth look at the support of overload function resolution in the presence of inheritance. Chapter 20 illustrates in detail how to use the C++ iostream input/output library. It provides explanation and examples of the general input and output of data, of defining class-specific instances of the input and output operators, of how to recognize and set condition states, and of how to format data. The iostream library is a class hierarchy implemented using both virtual and multiple inheritance. The C++ Primer concludes with an Appendix that provides a discussion and program example of each generic algorithm in alphabetical order for easy reference. Finally, whenever one writes a book, what one chooses to leave out is often as important as what one covers. Certain aspects of the language — such as a detailed discussion of how constructors work, under what conditions internal temporary objects are created by the compiler, or general concerns about efficiency — do not fit well into a tutorial introduction to the language, although they are of general importance to programming real-world applications. Prior to embarking on a third edition of C++ Primer, Stan wrote Inside the C++ Object Model (see [LIPPMAN96a] in the Bibliography at the end of this Preface) to cover much of this companion material. Often, the text refers to a discussion within the Object Model when readers may wish to have the more detailed explanation, particularly for the treatment of object-based and object-oriented programming. Certain portions of the C++ standard library have been intentionally left out, such as the support for locales and the numerical library. The C++ standard library is very extensive, and presenting all its aspects is beyond the scope of this primer. Some of the books in the Bibliography discuss the library in more detail (see [MUSSER96] and [STROUSTRUP97]). We believe that many books on various aspects of the C++ standard library will follow the publication of this book. Changes to the Third Edition The changes to the third edition fall into four general categories: 1. Coverage of new features added to the language: exception handling, run-time type identification, namespaces, the built-in bool type, and new-style cast notation. - 8 -