
本书是一本C++编程方面的优秀教材,全面介绍了面向对象编程的原理与方法,详细分析了与C++编程有关的技术。本书的主要内容包括类与对象、控制语句、函数与递归、数组、指针、运算符重载、继承、多态、输入/输出流、异常处理、文件处理、模板、搜索与排序等。全书以“活代码”的方式详细分析了每个知识要点,提供了丰富的自测练习和项目练习,是初学者和中高级程序员学习C++编程的理想用书。
Preface “The chief merit of language is clearness …” —Galen Welcome to the C++ computer programming language and C++ How to Program, Ninth Edition. This book presents leading-edge computing technologies. It’s appropriate for introductory course sequences based on the curriculum recommendations of two key professional organizations—the ACM and the IEEE. If you haven’t already done so, please read the back cover and inside back cover—these capture the essence of the book concisely. In this Preface we provide more detail for students, instructors and professionals. At the heart of the book is the Deitel signature live-code approach—we present concepts in the context of complete working programs followed by sample executions, rather than in code snippets. Read the online Before You Begin section(www.deitel.com/books/cpphtp9/cpphtp9_BYB.pdf) to learn how to set up your Linux-based, Windows-based or Apple OS X-based computer to run the hundreds of code examples. All the source code is available at www.deitel.com/books/cpphtp9 and www.pearsoninternational-editions.com/ deitel. Use the source code we provide to run each program as you study it. We believe that this book and its support materials will give you an informative, challenging and entertaining introduction to C++. As you read the book, if you have questions, we’re easy to reach at deitel@deitel.com—we’ll respond promptly. For book updates, visit www.deitel.com/books/cpphtp9, join our social media communities on Facebook(www.deitel.com/DeitelFan), Twitter(@deitel), Google+ (gplus.to/deitel) and LinkedIn(bit.ly/DeitelLinkedIn), and subscribe to the Deitel Buzz? Online newsletter (www.deitel.com/newsletter/subscribe.html). C++11 Standard The new C++11 standard, published in 2011, motivated us to write C++ How to Program, 9/e. Throughout the book, each new C++11 feature is marked with the “11” icon you see here in the margin. These are some of the key C++11 features of this new edition: ? Conforms to the new C++11 standard. Extensive coverage of the new C++11 features (Fig. 1). ? Code thoroughly tested on three popular industrial-strength C++11 compilers. We tested the code examples on GNU C++ 4.7, Microsoft? Visual C++? 2012 and Apple? LLVM in Xcode? 4.5. ? Smart pointers. Smart pointers help you avoid dynamic memory management errors by providing additional functionality beyond that of built-in pointers. We discuss unique_ptr in Chapter 17, and shared_ptr and weak_ptr in Chapter 24. ? Earlier coverage of Standard Library containers, iterators and algorithms, enhanced with C++11 capabilities. We moved the treatment of Standard Library containers, iterators and algorithms from Chapter 22 in the previous edition to Chapters 15 and 16 and enhanced it with additional C++11 features. The vast majority of your data structure needs can be fulfilled by reusing these Standard Library capabilities. We’ll show you how to build your own custom data structures in Chapter 19. C++11 features in C++ How to Program, 9/e Fig. 1 | A sampling of C++11 features in C++ How to Program, 9/e. ? Online Chapter 24, C++11: Additional Topics. In this chapter, we present additional C++11 topics. The new C++11 standard has been available since 2011, but not all C++ compilers have fully implemented the features. If all three of our key compilers already implemented a particular C++11 feature at the time we wrote this book, we generally integrated a discussion of that feature into the text with a live-code example. If any of these compilers had not implemented that feature, we included a bold italic heading followed by a brief discussion of the feature. Many of those discussions are expanded in online Chapter 24 as the features are implemented. This chapter includes discussions of regular expressions, shared_ptr and weak_ptr smart pointers, move semantics and more. ? Random Number generation, simulation and game playing. To help make programs more secure, we’ve added a treatment of C++11’s new non-deterministic random-number generation capabilities. Object-Oriented Programming ? Early-objects approach. The book introduces the basic concepts and terminology of object technology in Chapter 1. You’ll develop your first customized classes and objects in Chapter 3. Presenting objects and classes early gets you “thinking about objects” immediately and mastering these concepts more thoroughly. ? C++ Standard Library string. C++ offers two types of strings—string class objects (which we begin using in Chapter 3) and C strings. We’ve replaced most occurrences of C strings with instances of C++ class string to make programs more robust and eliminate many of the security problems of C strings. We continue to discuss C strings later in the book to prepare you for working with the legacy code that you’ll encounter in industry. In new development, you should favor string objects. ? C++ Standard Library array. Our primary treatment of arrays now uses the Standard Library’s array class template instead of built-in, C-style, pointer-based arrays. We still cover built-in arrays because they remain useful in C++ and so that you’ll be able to read legacy code. C++ offers three types of arrays—arrays and vectors (which we start using in Chapter 7) and C-style, pointer-based arrays which we discuss in Chapter 8. As appropriate, we use class template array instead of C arrays throughout the book. In new development, you should favor class template array objects. ? Crafting valuable classes. A key goal of this book is to prepare you to build valuable classes. In the Chapter 10 case study, you’ll build your own custom Array class, then in the Chapter 18 exercises you’ll convert it to a class template. You’ll truly appreciate the class concept. Chapter 10 begins with a test-drive of class template string so you can see an elegant use of operator overloading before you implement your own customized class with overloaded operators. ? Case studies in object-oriented programming. We provide case studies that span multiple sections and chapters and cover the software development lifecycle. These include the GradeBook class in Chapters 3–7, the Time class in Chapter 9 and the Employee class in Chapters 11–12. Chapter 12 contains a detailed diagram and explanation of how C++ can implement polymorphism, virtual functions and dynamic binding “under the hood.” ? Optional case study: Using the UML to develop an object-oriented design and C++ implementation of an ATM. The UML(Unified Modeling Language) is the industry-standard graphical language for modeling object-oriented systems. We introduce the UML in the early chapters. Online Chapters 25 and 26 include an optional case study on object-oriented design using the UML. We design and implement the software for a simple automated teller machine(ATM). We analyze a typical requirements document that specifies the system to be built. We determine the classes needed to implement that system, the attributes the classes need to have, the behaviors the classes need to exhibit and we specify how the classes must interact with one another to meet the system requirements. From the design we produce a complete C++ implementation. Students often report that the case study helps them “tie it all together” and truly understand object orientation. ? Exception handling. We integrate basic exception handling early in the book. Instructors can easily pull more detailed material forward from Chapter 17, Exception Handling: A Deeper Look. ? Custom template-based data structures. We provide a rich multi-chapter treatment of data structures—see the Data Structures module in the chapter dependency chart (Fig. 6). ? Three programming paradigms. We discuss structured programming, object-oriented programming and generic programming. Pedagogic Features ? Rich coverage of C++ fundamentals. We include a clear two-chapter treatment of control statements and algorithm development. ? Chapter 2 provides a simple introduction to C++ programming. ? Examples. We include a broad range of example programs selected from computer science, business, simulation, game playing and other topics (Fig. 2). ? Audience. The examples are accessible to computer science, information technology, software engineering and business students in novice-level and intermediate-level C++ courses. The book is also used by professional programmers. Examples Fig. 2 | A sampling of the book’s examples. ? Self-Review Exercises and Answers. Extensive self-review exercises and answers are included for self-study. ? Interesting, entertaining and challenging exercises. Each chapter concludes with a substantial set of exercises, including simple recall of important terminology and concepts, identifying the errors in code samples, writing individual program statements, writing small portions of C++ classes and member and non-member functions, writing complete programs and implementing major projects. Fig. 3 lists a sampling of the book’s exercises, including our Making a Difference exercises, which encourage you to use computers and the Internet to research and solve significant social problems. We hope you’ll approach these exercises with your own values, politics and beliefs. ? Illustrations and figures. Abundant tables, line drawings, UML diagrams, programs and program outputs are included. A sampling of the book’s drawings and diagrams is shown in (Fig. 4). Exercises Fig. 3 | A sampling of the book’s exercises. Drawings and diagrams Drawings and diagrams Fig. 4 | A sampling of the book’s drawings and diagrams. Other Features ? Pointers. We provide thorough coverage of the built-in pointer capabilities and the intimate relationship among built-in pointers, C strings and built-in arrays. ? Visual presentation of searching and sorting, with a simple explanation of Big O. ? Printed book contains core content; additional content is online. A few online chapters and appendices are included. ? Debugger appendices. We provide three debugger appendices on the book’s Companion Website— Appendix H, Using the Visual Studio Debugger, Appendix I, Using the GNU C++ Debugger and Appendix J, Using the Xcode Debugger. Secure C++ Programming It’s difficult to build industrial-strength systems that stand up to attacks from viruses, worms, and other forms of “malware.” Today, via the Internet, such attacks can be instantaneous and global in scope. Building security into software from the beginning of the development cycle can greatly reduce vulnerabilities. The CERT? Coordination Center(www.cert.org)was created to analyze and respond promptly to attacks. CERT—the Computer Emergency Response Team—is a government-funded organization within the Carnegie Mellon University Software Engineering Institute. CERT publishes and promotes secure coding standards for various popular programming languages to help software developers implement industrial strength systems that avoid the programming practices that leave systems open to attacks. We’d like to thank Robert C. Seacord, Secure Coding Manager at CERT and an adjunct professor in the Carnegie Mellon University School of Computer Science. Mr. Seacord was a technical reviewer for our book, C How to Program, 7/e, where he scrutinized our C programs from a security standpoint, recommending that we adhere to the CERT C Secure Coding Standard. We’ve done the same for C++ How to Program, 9/e, adhering to the CERT C++ Secure Coding Standard, which you can find at: We were pleased to discover that we’ve already been recommending many of these coding practices in our books. We upgraded our code and discussions to conform to these prac tices, as appropriate for an introductory/intermediate-level textbook. If you’ll be building industrial-strength C++ systems, consider reading Secure Coding in C and C++, Second Edition (Robert Seacord, Addison-Wesley Professional). Online Content The book’s Companion Website, which is accessible at contains the following chapters and appendices in searchable PDF format: ? Chapter 24, C++11: Additional Feature. ? Chapter 25, ATM Case Study, Part 1: Object-Oriented Design with the UML. ? Chapter 26, ATM Case Study, Part 2: Implementing an Object-Oriented Design. ? Appendix F, C Legacy Code Topics. ? Appendix G, UML 2: Additional Diagram Types. ? Appendix H, Using the Visual Studio Debugger. ? Appendix I, Using the GNU C++ Debugger. ? Appendix J, Using the Xcode Debugger. ? Appendix K, Test Driving a C++ Program on Mac OS X. (The test drives for Windows and Linux are in Chapter 1.) The Companion Website also includes: ? Building Your Own Compiler exercise descriptions from Chapter 19 (posted at the Companion Website and at www.deitel.com/books/cpphtp9). ? Chapter 1 test-drive for Mac OS X. Dependency Chart The chart in Fig. 5 shows the dependencies among the chapters to help instructors plan their syllabi. C++ How to Program, 9/e is appropriate for CS1 and many CS2 courses. The chart shows the book’s modular organization. Teaching Approach C++ How to Program, 9/e, contains a rich collection of examples. We stress program clarity and concentrate on building well-engineered software. Live-code approach. The book is loaded with “live-code” examples—most new concepts are presented in complete working C++ applications, followed by one or more executions showing program inputs and outputs. In the few cases where we use a code snippet, to ensure that it’s correct we tested it in a complete working program, then copied and pasted it into the book. Syntax coloring. For readability, we syntax color all the C++ code, similar to the way most C++ integrated- development environments and code editors syntax color code. Our coloring conventions are as follows: Code highlighting. We place light-blue shaded rectangles around key code segments. Using fonts for emphasis. We emphasize on-screen components in the bold Helvetica font (e.g., the File menu) and C++ program text in the Lucida font (for example, int x = 5;). Fig. 5 | Chapter Dependency Chart Objectives. The opening quotes are followed by a list of chapter objectives. Programming tips. We include programming tips to help you focus on key aspects of pro gram development. These tips and practices represent the best we’ve gleaned from a com bined seven decades of teaching and industry experience. Good Programming Practices The Good Programming Practices call attention to techniques that will help you pro duce programs that are clearer, more understandable and more maintainable. Common Programming Error Pointing out these Common Programming Errors reduces the likelihood that you’ll make them. Error-Prevention Tip These tips contain suggestions for exposing and removing bugs from your programs; many describe aspects of C++ that prevent bugs from getting into programs in the first place. Performance Tip These tips highlight opportunities for making your programs run faster or minimizing the amount of memory that they occupy. Portability Tip The Portability Tips help you write code that will run on a variety of platforms. Software Engineering Observation The Software Engineering Observations highlight architectural and design issues that affect the construction of software systems, especially large-scale systems. Summary Bullets. We present a section-by-section, bullet-list summary of the chapter. Index. We’ve included an extensive index. Obtaining the Software Used in C++ How to Program, 9/e We wrote the code examples in C++ How to Program, 9/e using the following C++ development tools: ? Microsoft’s free Visual Studio Express 2012 for Windows Desktop, which includes Visual C++ and other Microsoft development tools. This runs on Windows 7 and 8 and is available for download at ? GNU’s free GNU C++ (gcc.gnu.org/install/binaries.html), which is already installed on most Linux systems and can also be installed on Mac OS X and Windows systems. ? Apple’s free Xcode, which OS X users can download from the Mac App Store. Instructor Supplements The following supplements are available to qualified instructors only through Pearson Education’s Instructor Resource Center (www.pearsoninternationaleditions.com/deitel): ? Solutions Manual contains solutions to most of the end-of-chapter exercises. We’ve added many Making a Difference exercises, most with solutions. Please do not write to us requesting access to the Pearson Instructor’s Resource Center. Access is restricted to college instructors teaching from the book. Instructors may obtain access only through their Pearson representatives. If you’re not a registered faculty member, contact your Pearson representative. Exercise Solutions are not provided for “project” exercises. Check out our Programming Projects Resource Center for lots of additional exercise and project possibilities. ? Test Item File of multiple-choice questions (approximately two per book section). ? Customizable PowerPoint? slides containing all the code and figures in the text, plus bulleted items that summarize the key points in the text. Online Practice and Assessment with MyProgrammingLab MyProgrammingLab helps students fully grasp the logic, semantics, and syntax of programming. Through practice exercises and immediate, personalized feedback, MyProgrammingLab improves the programming competence of beginning students who often struggle with the basic concepts and paradigms of popular high-level programming languages. A self-study and homework tool, a MyProgrammingLab course consists of hundreds of small practice problems organized around the structure of this textbook. For students, the system automatically detects errors in the logic and syntax of their code submissions and offers targeted hints that enable students to figure out what went wrong—and why. For instructors, a comprehensive gradebook tracks correct and incorrect answers and stores the code inputted by students for review. For a full demonstration, to see feedback from instructors and students or to get started using MyProgrammingLab in your course, visit www.myprogramminglab.com. Acknowledgments We’d like to thank Abbey Deitel and Barbara Deitel of Deitel & Associates, Inc. for long hours devoted to this project. Abbey co-authored Chapter 1 and she and Barbara painstakingly researched the new capabilities of C++11. We’re fortunate to have worked with the dedicated team of publishing professionals at Pearson Higher Education. We appreciate the guidance, wisdom and energy of Tracy Johnson, Executive Editor, Computer Science. Carole Snyder did an extraordinary job recruiting the book’s reviewers and managing the review process. Bob Engelhardt did a wonderful job bringing the book to publication. Reviewers We wish to acknowledge the efforts of our reviewers. The book was scrutinized by current and former members of the C++ standards committee that developed C++11, academics teaching C++ courses and industry experts. They provided countless suggestions for improving the presentation. Any remaining flaws in the book are our own. Ninth Edition reviewers: Dean Michael Berris (Google, Member ISO C++ Com mittee), Danny Kalev (C++ expert, certified system analyst and former member of the C++ Standards Committee), Linda M. Krause (Elmhurst College), James P. McNellis (Microsoft Corporation), Robert C. Seacord (Secure Coding Manager at SEI/CERT, author of Secure Coding in C and C++) and José Antonio González Seco (Parliament of Andalusia). Other recent edition reviewers: Virginia Bailey (Jackson State University), Thomas J. Borrelli (Rochester Institute of Technology), Ed Brey (Kohler Co.), Chris Cox (Adobe Systems), Gregory Dai (eBay), Peter J. DePasquale (The College of New Jersey), John Dibling (SpryWare), Susan Gauch (University of Arkansas), Doug Gregor (Apple, Inc.), Jack Hagemeister (Washington State University), Williams M. Higdon (University of Indiana), Anne B. Horton (Lockheed Martin), Terrell Hull (Logicalis Integration Solu tions), Ed James-Beckham (Borland), Wing-Ning Li (University of Arkansas), Dean Mathias (Utah State University), Robert A. McLain (Tidewater Community College), Robert Myers (Florida State University), Gavin Osborne (Saskatchewan Inst. of App. Sci. and Tech.), Amar Raheja (California State Polytechnic University, Pomona), April Reagan (Microsoft), Raymond Stephenson (Microsoft), Dave Topham (Ohlone College), Anthony Williams (author and C++ Standards Committee member) and Chad Willwerth (University Washington, Tacoma). As you read the book, we’d sincerely appreciate your comments, criticisms and suggestions for improving the text. Please address all correspondence to: We’ll respond promptly. We enjoyed writing C++ How to Program, Ninth Edition. We hope you enjoy reading it! Paul Deitel Harvey Deitel About the Authors Paul Deitel, CEO and Chief Technical Officer of Deitel & Associates, Inc., is a graduate of MIT, where he studied Information Technology. Through Deitel & Associates, Inc., he has delivered hundreds of programming courses to industry clients, including Cisco, IBM, Siemens, Sun Microsystems, Dell, Fidelity, NASA at the Kennedy Space Center, the National Severe Storm Laboratory, White Sands Missile Range, Rogue Wave Software, Boeing, SunGard Higher Education, Nortel Networks, Puma, iRobot, Invensys and many more. He and his co-author, Dr. Harvey M. Deitel, are the world’s best-selling programming-language textbook/professional book/video authors. Dr. Harvey Deitel, Chairman and Chief Strategy Officer of Deitel & Associates, Inc., has 50 years of experience in the computer field. Dr. Deitel earned B.S. and M.S. degrees in Electrical Engineering from MIT and a Ph.D. in Mathematics from Boston University. He has extensive college teaching experience, including earning tenure and serving as the Chairman of the Computer Science Department at Boston College before founding Deitel & Associates, Inc., in 1991 with his son, Paul Deitel. The Deitels’ publications have earned international recognition, with translations published in Chinese, Korean, Japanese, German, Russian, Spanish, French, Polish, Italian, Portuguese, Greek, Urdu and Turkish. Dr. Deitel has delivered hundreds of programming courses to corporate, academic, government and military clients. Corporate Training from Deitel & Associates, Inc. Deitel & Associates, Inc., founded by Paul Deitel and Harvey Deitel, is an internationally recognized authoring and corporate training organization, specializing in computer programming languages, object technology, mobile app development and Internet and web software technology. The company’s clients include many of the world’s largest companies, government agencies, branches of the military, and academic institutions. The company offers instructor-led training courses delivered at client sites worldwide on major programming languages and platforms, including C++, Visual C++?, C, Java, Visual C#?, Visual Basic?, XML?, Python?, object technology, Internet and web programming, Android app development, Objective-C and iPhone app development and a growing list of additional programming and software development courses. Through its 36-year publishing partnership with Prentice Hall/Pearson, Deitel & Associates, Inc., publishes leading-edge programming college textbooks, professional books and LiveLessons video courses. Deitel & Associates, Inc. and the authors can be reached at: To learn more about Deitel’s Dive-Into? Series Corporate Training curriculum, visit: To request a proposal for worldwide on-site, instructor-led training at your organization, e-mail deitel@deitel.com. Individuals wishing to purchase Deitel books and LiveLessons video training can do so through www.deitel.com. Bulk orders by corporations, the government, the military and academic institutions should be placed directly with Pearson.
Contents Chapter 1 Introduction to Computers and C++ 1 1.1 Introduction 2 1.2 Computers and the Internet in Industry and Research 2 1.3 Hardware and Software 4 1.4 Data Hierarchy 6 1.5 Machine Languages, Assembly Languages and High-Level Languages 7 1.6 C++ 8 1.7 Programming Languages 9 1.8 Introduction to Object Technology 10 1.9 Typical C++ Development Environment 13 1.10 Test-Driving a C++ Application 15 1.11 Operating Systems 20 1.12 The Internet and World Wide Web 22 1.13 Some Key Software Development Terminology 23 1.14 C++11 and the Open Source Boost Libraries 25 1.15 Keeping Up to Date with Information Technologies 25 1.16 Web Resources 26 Chapter 2 Introduction to C++ Programming; Input/Output and Operators 31 2.1 Introduction 31 2.2 First Program in C++: Printing a Line of Text 32 2.3 Modifying Our First C++ Program 35 2.4 Another C++ Program: Adding Integers 36 2.5 Memory Concepts 39 2.6 Arithmetic 40 2.7 Decision Making: Equality and Relational Operators 43 2.8 Wrap-Up 47 Chapter 3 Introduction to Classes, Objects and Strings 55 3.1 Introduction 55 3.2 Defining a Class with a Member Function 56 3.3 Defining a Member Function with a Parameter 58 3.4 Data Members, set Member Functions and get Member Functions 61 3.5 Initializing Objects with Constructors 66 3.6 Placing a Class in a Separate File for Reusability 69 3.7 Separating Interface from Implementation 72 3.8 Validating Data with set Functions 76 3.9 Wrap-Up 80 Chapter 4 Control Statements: Part 1; Assignment, ++ and - - Operators 87 4.1 Introduction 87 4.2 Algorithms 88 4.3 Pseudocode 88 4.4 Control Structures 89 4.5 if Selection Statement 92 4.6 if…else Double-Selection Statement 93 4.7 while Repetition Statement 97 4.8 Formulating Algorithms: Counter-Controlled Repetition 98 4.9 Formulating Algorithms: Sentinel-Controlled Repetition 103 4.10 Formulating Algorithms: Nested Control Statements 111 4.11 Assignment Operators 116 4.12 Increment and Decrement Operators 116 4.13 Wrap-Up 118 Chapter 5 Control Statements: Part 2; Logical Operators 131 5.1 Introduction 131 5.2 Essentials of Counter-Controlled Repetition 132 5.3 for Repetition Statement 133 5.4 Examples Using the for Statement 136 5.5 do…while Repetition Statement 140 5.6 switch Multiple-Selection Statement 141 5.7 break and continue Statements 148 5.8 Logical Operators 150 5.9 Confusing the Equality (==) and Assignment (=) Operators 153 5.10 Structured Programming Summary 154 5.11 Wrap-Up 158 Chapter 6 Functions and an Introduction to Recursion 167 6.1 Introduction 168 6.2 Program Components in C++ 168 6.3 Math Library Functions 169 6.4 Function Definitions with Multiple Parameters 170 6.5 Function Prototypes and Argument Coercion 174 6.6 C++ Standard Library Headers 176 6.7 Case Study: Random Number Generation 177 6.8 Case Study: Game of Chance; Introducing enum 182 6.9 C++11 Random Numbers 185 6.10 Storage Classes and Storage Duration 186 6.11 Scope Rules 189 6.12 Function Call Stack and Activation Records 191 6.13 Functions with Empty Parameter Lists 194 6.14 Inline Functions 195 6.15 References and Reference Parameters 196 6.16 Default Arguments 198 6.17 Unary Scope Resolution Operator 200 6.18 Function Overloading 200 6.19 Function Templates 203 6.20 Recursion 205 6.21 Example Using Recursion: Fibonacci Series 208 6.22 Recursion vs. Iteration 210 6.23 Wrap-Up 213 Chapter 7 Class Templates array and vector; Catching Exceptions 232 7.1 Introduction 233 7.2 arrays 233 7.3 Declaring arrays 234 7.4 Examples Using arrays 235 7.5 Range-Based for Statement 244 7.6 Case Study: Class GradeBook Using an array to Store Grades 246 7.7 Sorting and Searching arrays 251 7.8 Multidimensional arrays 252 7.9 Case Study: Class GradeBook Using a Two-Dimensional array 255 7.10 Introduction to C++ Standard Library Class Template vector 260 7.11 Wrap-Up 264 Chapter 8 Pointers 279 8.1 Introduction 280 8.2 Pointer Variable Declarations and Initialization 280 8.3 Pointer Operators 281 8.4 Pass-by-Reference with Pointers 283 8.5 Built-In Arrays 287 8.6 Using const with Pointers 289 8.7 sizeof Operator 292 8.8 Pointer Expressions and Pointer Arithmetic 294 8.9 Relationship Between Pointers and Built-In Arrays 296 8.10 Pointer-Based Strings 299 8.11 Wrap-Up 301 Chapter 9 Classes: A Deeper Look; Throwing Exceptions 316 9.1 Introduction 317 9.2 Time Class Case Study 317 9.3 Class Scope and Accessing Class Members 323 9.4 Access Functions and Utility Functions 324 9.5 Time Class Case Study: Constructors with Default Arguments 324 9.6 Destructors 328 9.7 When Constructors and Destructors Are Called 329 9.8 Time Class Case Study: A Subtle Trap— Returning a Reference or a Pointer to a private Data Member 331 9.9 Default Memberwise Assignment 334 9.10 const Objects and const Member Functions 335 9.11 Composition: Objects as Members of Classes 337 9.12 friend Functions and friend Classes 341 9.13 Using the this Pointer 343 9.14 static Class Members 347 9.15 Wrap-Up 351 Chapter 10 Operator Overloading; Class string 361 10.1 Introduction 362 10.2 Using the Overloaded Operators of Standard Library Class string 362 10.3 Fundamentals of Operator Overloading 365 10.4 Overloading Binary Operators 366 10.5 Overloading the Binary Stream Insertion and Stream Extraction Operators 367 10.6 Overloading Unary Operators 370 10.7 Overloading the Unary Prefix and Postfix ++ and -- Operators 370 10.8 Case Study: A Date Class 371 10.9 Dynamic Memory Management 375 10.10 Case Study: Array Class 377 10.11 Operators as Member vs. Non-Member Functions 387 10.12 Converting Between Types 388 10.13 explicit Constructors and Conversion Operators 389 10.14 Overloading the Function Call Operator () 391 10.15 Wrap-Up 392 Chapter 11 Object-Oriented Programming: Inheritance 402 11.1 Introduction 402 11.2 Base Classes and Derived Classes 403 11.3 Relationship between Base and Derived Classes 405 11.4 Constructors and Destructors in Derived Classes 422 11.5 public, protected and private Inheritance 424 11.6 Software Engineering with Inheritance 425 11.7 Wrap-Up 425 Chapter 12 Object-Oriented Programming: Polymorphism 431 12.1 Introduction 432 12.2 Introduction to Polymorphism: Polymorphic Video Game 432 12.3 Relationships Among Objects in an Inheritance Hierarchy 433 12.4 Type Fields and switch Statements 443 12.5 Abstract Classes and Pure virtual Functions 444 12.6 Case Study: Payroll System Using Polymorphism 445 12.7 (Optional) Polymorphism, Virtual Functions and Dynamic Binding “Under the Hood” 456 12.8 Case Study: Payroll System Using Polymorphism and Runtime Type Information with Downcasting, dynamic_cast, typeid and type_info 459 12.9 Wrap-Up 462 Chapter 13 Stream Input/Output: A Deeper Look 468 13.1 Introduction 469 13.2 Streams 469 13.3 Stream Output 472 13.4 Stream Input 473 13.5 Unformatted I/O Using read, write and gcount 476 13.6 Introduction to Stream Manipulators 477 13.7 Stream Format States and Stream Manipulators 481 13.8 Stream Error States 488 13.9 Tying an Output Stream to an Input Stream 490 13.10 Wrap-Up 490 Chapter 14 File Processing 499 14.1 Introduction 499 14.2 Files and Streams 500 14.3 Creating a Sequential File 500 14.4 Reading Data from a Sequential File 504 14.5 Updating Sequential Files 508 14.6 Random-Access Files 508 14.7 Creating a Random-Access File 509 14.8 Writing Data Randomly to a Random-Access File 513 14.9 Reading from a Random-Access File Sequentially 514 14.10 Case Study: A Transaction-Processing Program 516 14.11 Object Serialization 521 14.12 Wrap-Up 521 Chapter 15 Standard Library Containers and Iterators 530 15.1 Introduction 531 15.2 Introduction to Containers 532 15.3 Introduction to Iterators 535 15.4 Introduction to Algorithms 538 15.5 Sequence Containers 539 15.6 Associative Containers 550 15.7 Container Adapters 557 15.8 Class bitset 561 15.9 Wrap-Up 562 Chapter 16 Standard Library Algorithms 573 16.1 Introduction 573 16.2 Minimum Iterator Requirements 574 16.3 Algorithms 575 16.4 Function Objects 600 16.5 Lambda Expressions 603 16.6 Standard Library Algorithm Summary 604 16.7 Wrap-Up 605 Chapter 17 Exception Handling: A Deeper Look 613 17.1 Introduction 613 17.2 Example: Handling an Attempt to Divide by Zero 614 17.3 Rethrowing an Exception 618 17.4 Stack Unwinding 620 17.5 When to Use Exception Handling 621 17.6 Constructors, Destructors and Exception Handling 622 17.7 Exceptions and Inheritance 622 17.8 Processing new Failures 623 17.9 Class unique_ptr and Dynamic Memory Allocation 625 17.10 Standard Library Exception Hierarchy 627 17.11 Wrap-Up 628 Chapter 18 Introduction to Custom Templates 634 18.1 Introduction 634 18.2 Class Templates 635 18.3 Function Template to Manipulate a Class-Template Specialization Object 638 18.4 Nontype Parameters 640 18.5 Default Arguments for Template Type Parameters 640 18.6 Overloading Function Templates 640 18.7 Wrap-Up 641 Chapter 19 Custom Templatized Data Structures 644 19.1 Introduction 644 19.2 Self-Referential Classes 645 19.3 Linked Lists 646 19.4 Stacks 657 19.5 Queues 660 19.6 Trees 663 19.7 Wrap-Up 669 Chapter 20 Searching and Sorting 680 20.1 Introduction 680 20.2 Searching Algorithms 681 20.3 Sorting Algorithms 687 20.4 Wrap-Up 696 Chapter 21 Class string and String Stream Processing: A Deeper Look 702 21.1 Introduction 703 21.2 string Assignment and Concatenation 704 21.3 Comparing strings 705 21.4 Substrings 707 21.5 Swapping strings 708 21.6 string Characteristics 708 21.7 Finding Substrings and Characters in a string 710 21.8 Replacing Characters in a string 711 21.9 Inserting Characters into a string 713 21.10 Conversion to Pointer-Based char * Strings 713 21.11 Iterators 715 21.12 String Stream Processing 715 21.13 C++11 Numeric Conversion Functions 718 21.14 Wrap-Up 719 Chapter 22 Bits, Characters, C Strings and structs 726 22.1 Introduction 727 22.2 Structure Definitions 727 22.3 typedef 728 22.4 Example: Card Shuffling and Dealing Simulation 728 22.5 Bitwise Operators 730 22.6 Bit Fields 737 22.7 Character-Handling Library 740 22.8 C String-Manipulation Functions 744 22.9 C String-Conversion Functions 749 22.10 Search Functions of the C String-Handling Library 753 22.11 Memory Functions of the C String-Handling Library 756 22.12 Wrap-Up 759 Chapter 23 Other Topics 773 23.1 Introduction 773 23.2 const_cast Operator 774 23.3 mutable Class Members 775 23.4 namespaces 776 23.5 Operator Keywords 779 23.6 Pointers to Class Members (.* and ->*) 781 23.7 Multiple Inheritance 782 23.8 Multiple Inheritance and virtual Base Classes 786 23.9 Wrap-Up 789 Appendix A Operator Precedence and Associativity 794 Appendix B ASCII Character Set 796 Appendix C Fundamental Types 797 Appendix D Number Systems 799 Appendix E Preprocessor 809 Index 819 本书的第24章~第26章、附录F~附录K请登录华信教育资源网(www.hxedu.com.cn)下载。 Chapter 24 C++11: Additional Features Chapter 25 ATM Case Study, Part 1: Object-Oriented Design with the UML Chapter 26 ATM Case Study, Part 2: Implementing an Object-Oriented Design Appendix F C Legacy Code Topics Appendix G UML 2: Additional Diagram Types Appendix H Using the Visual Studio Debugger Appendix I Using the GNU C++ Debugger Appendix J Using the Xcode Debugger Appendix K Test Driving a C++ Program on Mac OS X