Tài liệu Thinking in C++ Second Edition pdf

1.1K 853 9
Tài liệu Thinking in C++ Second Edition pdf

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Thinking In C++ Bruce Eckel President, MindView Inc. Prentice Hall PTR Upper Saddle River, New Jersey 07458 http://www.phptr.com Publisher: Alan Apt Production Editor: Mona Pompilli Development Editor: Sondra Chavez Book Design, Cover Design and Cover Photo: Daniel Will-Harris, daniel@will-harris.com Copy Editor: Shirley Michaels Production Coordinator: Lori Bulwin Editorial Assistant: Shirley McGuire © 1999 by Bruce Eckel, MindView, Inc. Published by Prentice Hall Inc. A Paramount Communications Company Englewood Cliffs, New Jersey 07632 The information in this book is distributed on an “as is” basis, without warranty. While every precaution has been taken in the preparation of this book, neither the author nor the publisher shall have any liability to any person or entitle with respect to any liability, loss or damage caused or alleged to be caused directly or indirectly by instructions contained in this book or by the computer software or hardware products described herein. All rights reserved. No part of this book may be reproduced in any form or by any electronic or mechanical means including information storage and retrieval systems without permission in writing from the publisher or author, except by a reviewer who may quote brief passages in a review. Any of the names used in the examples and text of this book are fictional; any relationship to persons living or dead or to fictional characters in other works is purely coincidental. Printed in the United States of America 10 9 8 7 6 5 4 3 2 1 ISBN 0-13-917709-4 Prentice-Hall International (UK) Limited, London Prentice-Hall of Australia Pty. Limited, Sydney Prentice-Hall Canada, Inc., Toronto Prentice-Hall Hisapnoamericana, S.A., Mexico Prentice-Hall of India Private Limited, New Delhi Prentice-Hall of Japan, Inc., Tokyo Simon & Schuster Asia Pte. Ltd., Singapore Editora Prentice-Hall do Brasil, Ltda., Rio de Janeiro dedication to the scholar, the healer, and the muse What’s inside . Thinking in C++ 2 nd edition VERSION TICA17 1 Preface 17 Prerequisites .17 Thinking in C 17 Learning C++ .18 Goals 19 Chapters 20 Exercises 23 Source code 24 Coding standards 25 Language standards 26 Language support .26 Seminars & CD Roms 26 Errors 27 Acknowledgements 27 1: Introduction to objects 29 The progress of abstraction 29 An object has an interface 31 The hidden implementation 33 Reusing the implementation 34 Inheritance: reusing the interface35 Is-a vs. is-like-a relationships . 39 Interchangeable objects with polymorphism 40 Creating and destroying objects .43 Exception handling: dealing with errors 44 Analysis and design 45 Phase 0: Make a plan 47 Phase 1: What are we making? .48 Phase 2: How will we build it? . 50 Phase 3: Build it .53 Phase 4: Iteration 53 Plans pay off . 55 Why C++ succeeds .55 A better C .56 You’re already on the learning curve 56 Efficiency .56 Systems are easier to express and understand 57 Maximal leverage with libraries . 57 Source-code reuse with templates . 57 Error handling .57 Programming in the large . 58 Strategies for transition 58 Guidelines . 58 Management obstacles 60 Summary 61 2: Making & using objects 63 The process of language translation63 Interpreters 64 Compilers .64 The compilation process .65 Tools for separate compilation . 66 Declarations vs. definitions .67 Linking .71 Using libraries 72 Your first C++ program 73 Using the iostreams class 73 Namespaces 74 Fundamentals of program structure 75 "Hello, world!" .76 Running the compiler .77 More about iostreams . 77 Character array concatenation . 78 Reading input .78 Simple file manipulation .79 Introducing string s 80 Reading and writing files . 82 Introducing vector .84 Summary 87 Exercises 88 3: The C in C++ 91 Creating functions 91 Using the C function library . 94 Creating your own libraries with the librarian 94 Controlling execution .95 True and false . 95 if-else 95 while . 96 do-while . 97 for . 98 The break and continue Keywords 99 switch . 100 Recursion 102 Introduction to operators 102 Precedence 103 Auto increment and decrement . 103 Introduction to data types .104 Basic built-in types . 104 bool , true , & false 105 Specifiers 106 Introduction to Pointers 108 Modifying the outside object 112 Introduction to C++ references . 114 Pointers and references as modifiers115 Scoping .117 Defining variables on the fly 118 Specifying storage allocation .120 Global variables 120 Local variables . 121 static . 121 extern . 123 Constants 124 volatile . 125 Operators and their use .126 Assignment . 126 Mathematical operators 126 Relational operators 128 Logical operators 128 Bitwise operators 129 Shift operators 129 Unary operators 132 The ternary operator . 133 The comma operator . 133 Common pitfalls when using operators134 Casting operators 134 sizeof – an operator by itself . 135 The asm keyword . 135 Explicit operators 135 Composite type creation .136 Aliasing names with typedef 136 Combining variables with struct 137 Clarifying programs with enum . 140 Saving memory with union 141 Arrays . 142 Debugging hints .150 Debugging flags . 151 Turning variables and expressions into strings .152 The C assert( ) macro .153 Make: an essential tool for separate compilation 154 Make activities 155 Makefile s in this book 157 An example makefile .158 Summary 160 Exercises 160 4: Data abstraction 163 A tiny C-like library .164 Dynamic storage allocation 167 Bad guesses 170 What's wrong? 171 The basic object . 172 What's an object? . 178 Abstract data typing . 179 Object details .179 Header file etiquette .181 Importance of header files 181 The multiple-declaration problem .183 The preprocessor directives #define , #ifdef and #endif 183 A standard for header files 184 Namespaces in headers .185 Using headers in projects 185 Nested structures 186 Global scope resolution 189 Summary 190 Exercises 190 5: Hiding the implementation 195 Setting limits 195 C++ access control .196 protected 198 Friends .198 Nested friends . 200 Is it pure? 203 Object layout 203 The class 204 Modifying Stash to use access control206 Modifying Stack to use access control207 Handle classes 208 Hiding the implementation . 208 Reducing recompilation 208 Summary 211 Exercises 211 6: Initialization & cleanup 213 Guaranteed initialization with the constructor 214 Guaranteed cleanup with the destructor 215 Elimination of the definition block217 for loops . 219 Storage allocation . 220 Stash with constructors and destructors 221 Stack with constructors & destructors 224 Aggregate initialization 227 Default constructors .229 Summary 230 Exercises 231 7: Function overloading & default arguments 233 More name decoration 234 Overloading on return values 235 Type-safe linkage . 235 Overloading example .236 unions .239 Default arguments 243 Placeholder arguments 244 Choosing overloading vs. default arguments .244 Summary 249 Exercises 249 8: Constants 251 Value substitution .251 const in header files 252 Safety const s 253 Aggregates 254 Differences with C 254 Pointers .255 Pointer to const 256 const pointer . 256 Assignment and type checking . 257 Function arguments & return values 258 Passing by const value . 258 Returning by const value 259 Passing and returning addresses 262 Classes 265 const and enum in classes 265 Compile-time constants in classes 268 const objects & member functions.271 ROMability .275 volatile .275 Summary 277 Exercises 277 9: Inline functions 281 Preprocessor pitfalls .281 Macros and access 284 Inline functions 285 Inlines inside classes .285 Access functions . 286 Stash & Stack with inlines .292 Inlines & the compiler 292 Limitations 292 Order of evaluation . 293 Hidden activities in constructors & destructors 294 Forward referencing .295 Reducing clutter . 295 More preprocessor features 296 Token pasting . 297 Improved error checking 297 Summary 300 Exercises 300 10: Name control 303 Static elements from C . 303 static variables inside functions 303 Controlling linkage . 307 Other storage class specifiers 309 Namespaces .309 Creating a namespace .309 Using a namespace . 311 Static members in C++ .315 Defining storage for static data members .315 Nested and local classes 317 static member functions .318 Static initialization dependency321 What to do 322 Alternate linkage specifications324 Summary 325 Exercises 325 11: References & the copy- constructor 327 Pointers in C++ 327 References in C++ 328 References in functions .328 Argument-passing guidelines 331 The copy-constructor . 331 Passing & returning by value 331 Copy-construction 336 Default copy-constructor 341 Alternatives to copy-construction .344 Pointers to members .345 Functions 346 Summary 349 Exercises 349 12: Operator overloading 351 Warning & reassurance .351 Syntax .352 Overloadable operators .353 Unary operators 353 Binary operators . 358 Arguments & return values . 369 Unusual operators . 371 Operators you can’t overload 375 Nonmember operators 375 Basic guidelines 377 Overloading assignment .378 Behavior of operator= . 379 Automatic type conversion .389 Constructor conversion . 389 Operator conversion . 391 A perfect example: strings 393 Pitfalls in automatic type conversion395 Summary 397 Exercises 397 13: Dynamic object creation 399 Object creation .400 C’s approach to the heap . 401 operator new . 402 operator delete 403 A simple example .403 Memory manager overhead 404 Early examples redesigned .405 Stash for pointers .405 The stack 409 new & delete for arrays .411 Making a pointer more like an array412 Running out of storage .412 Overloading new & delete 413 Overloading global new & delete .414 Overloading new & delete for a class416 Overloading new & delete for arrays418 Constructor calls . 420 Object placement 421 Summary 423 Exercises 423 14: Inheritance & composition 425 Composition syntax . 425 Inheritance syntax 427 The constructor initializer list 429 Member object initialization . 429 Built-in types in the initializer list .429 Combining composition & inheritance 430 Order of constructor & destructor calls432 Name hiding . 434 Functions that don’t automatically inherit .435 Choosing composition vs. inheritance 436 Subtyping . 438 Specialization .440 private inheritance .442 protected .443 protected inheritance . 444 Multiple inheritance . 445 Incremental development . 445 Upcasting . 446 Why “upcasting”? . 447 Upcasting and the copy-constructor (not indexed) .447 Composition vs. inheritance (revisited)450 Pointer & reference upcasting .451 A crisis .452 Summary 452 Exercises 452 15: Polymorphism & virtual functions 455 Evolution of C++ programmers 455 Upcasting . 456 The problem .457 Function call binding 458 virtual functions 458 Extensibility 459 How C++ implements late binding462 Storing type information .463 Picturing virtual functions 464 Under the hood . 466 Installing the vpointer .467 Objects are different . 467 Why virtual functions? 468 Abstract base classes and pure virtual functions 469 Pure virtual definitions 474 Inheritance and the VTABLE 475 virtual functions & constructors479 Order of constructor calls . 480 Behavior of virtual functions inside constructors 481 Destructors and virtual destructors482 Virtuals in destructors . 483 Summary 484 Exercises 484 16: Introduction to templates 487 Containers & iterators 487 The need for containers 489 Overview of templates 490 The C approach 490 The Smalltalk approach 490 The template approach 492 Template syntax 493 Non-inline function definitions . 495 The stack as a template . 496 Constants in templates 498 Stash and stack as templates 500 The ownership problem 500 Stash as a template . 500 stack as a template . 506 Polymorphism & containers .509 Summary 513 Exercises 513 Part 2: The Standard C++ Library 515 Library overview 516 17: Strings 519 What’s in a string 519 Creating and initializing C++ strings521 Operating on strings .523 Appending, inserting and concatenating strings . 524 Replacing string characters . 525 Concatenation using non-member overloaded operators .529 Searching in strings 530 Finding in reverse .535 Finding first/last of a set . 536 Removing characters from strings 537 Comparing strings 541 Using iterators 545 Strings and character traits 547 A string application 550 Summary 553 Exercises 554 18: Iostreams 555 Why iostreams? 555 True wrapping 557 Iostreams to the rescue . 559 Sneak preview of operator overloading560 Inserters and extractors .561 Common usage . 562 Line-oriented input .564 File iostreams . 566 Open modes 568 Iostream buffering 568 Using get( ) with a streambuf .570 Seeking in iostreams 570 Creating read/write files .572 stringstreams 573 strstreams .573 User-allocated storage 573 Automatic storage allocation 576 Output stream formatting .579 Internal formatting data 580 An exhaustive example . 584 Formatting manipulators 587 Manipulators with arguments .589 Creating manipulators 592 Effectors . 593 Iostream examples 595 Code generation 595 A simple datalogger 603 Counting editor .610 Breaking up big files .611 Summary 613 Exercises 613 19: Templates in depth 615 Nontype template arguments 615 Default template arguments .616 The typename keyword 616 Typedefing a typename .618 Using typename instead of class 618 Function templates . 618 A memory allocation system 619 Type induction in function templates 623 Taking the address of a generated function template . 624 Applying a function to an STL sequence . 625 Template-templates 628 Member function templates .629 Why virtual member template functions are disallowed . 631 Nested template classes 631 Template specializations .631 Full specialization . 631 Partial Specialization 631 A practical example 631 Design & efficiency 635 Preventing template bloat . 635 Explicit instantiation 636 Explicit specification of template functions .637 Controlling template instantiation637 The inclusion vs. separation models639 The export keyword 639 Template programming idioms.639 The “curiously-recurring template” 639 Traits 639 Summary 639 20: STL Containers & Iterators 641 Containers and iterators 641 STL reference documentation . 643 The Standard Template Library 643 The basic concepts .645 Containers of strings .649 Inheriting from STL containers 651 A plethora of iterators 653 Iterators in reversible containers . 655 Iterator categories .656 Predefined iterators . 657 Basic sequences: vector, list & deque 663 Basic sequence operations 663 vector 666 Cost of overflowing allocated storage667 Inserting and erasing elements 671 deque 673 Converting between sequences . 675 Cost of overflowing allocated storage676 Checked random-access 678 list .679 Special list operations . 681 Swapping all basic sequences .685 Robustness of lists 686 Performance comparison 687 set .692 Eliminating strtok( ) 693 StreamTokenizer : a more flexible solution . 695 A completely reusable tokenizer . 697 stack .702 queue 705 Priority queues .710 Holding bits 720 bitset<n> 720 vector<bool> .724 Associative containers 726 Generators and fillers for associative containers .730 The magic of maps .733 Multimaps and duplicate keys 738 Multisets .741 Combining STL containers 744 Cleaning up containers of pointers747 Creating your own containers 749 Freely-available STL extensions751 Summary 753 Exercises 754 21: STL Algorithms 757 Function objects . 757 Classification of function objects 759 Automatic creation of function objects759 SGI extensions 773 A catalog of STL algorithms 779 Support tools for example creation. 781 Filling & generating 785 Counting . 787 Manipulating sequences 788 Searching & replacing 793 Comparing ranges . 799 Removing elements 802 Sorting and operations on sorted ranges805 Heap operations 816 Applying an operation to each element in a range 817 Numeric algorithms 825 General utilities 828 Creating your own STL-style algorithms 830 Summary 831 Exercises 831 Part 3: Advanced Topics 835 22: Multiple inheritance 836 Perspective . 836 Duplicate subobjects 838 Ambiguous upcasting . 839 virtual base classes 840 The "most derived" class and virtual base initialization 842 "Tying off" virtual bases with a default constructor 843 Overhead 845 Upcasting 846 Persistence 849 Avoiding MI .856 Repairing an interface 856 Summary 861 Exercises 861 23: Exception handling 863 Error handling in C .863 Throwing an exception .866 Catching an exception 866 The try block 867 Exception handlers . 867 The exception specification 868 Better exception specifications? . 871 Catching any exception 871 Rethrowing an exception 872 Uncaught exceptions . 872 Function-level try blocks 874 Cleaning up 874 Constructors .878 Making everything an object 879 Exception matching 882 Standard exceptions 884 Programming with exceptions 885 When to avoid exceptions . 885 Typical uses of exceptions 886 Overhead 890 Summary 890 Exercises 891 24: Run-time type identification 893 The “Shape” example .893 What is RTTI? 894 Two syntaxes for RTTI . 894 Syntax specifics 898 typeid( ) with built-in types 898 Producing the proper type name . 899 Nonpolymorphic types . 899 Casting to intermediate levels . 900 void pointers . 902 Using RTTI with templates 902 References 903 Exceptions 904 Multiple inheritance .905 Sensible uses for RTTI .906 Revisiting the trash recycler . 907 Mechanism & overhead of RTTI910 Creating your own RTTI 910 Explicit cast syntax 914 static_cast 915 const_cast 917 reinterpret_cast .918 Summary 920 Exercises 921 XX: Maintaining system integrity 923 The canonical object form 923 An extended canonical form . 923 Dynamic aggregation .923 Reference counting 927 Reference-counted class hierarchies 927 Exercises 927 25: Design patterns 929 The pattern concept 929 The singleton 930 Classifying patterns 934 Features, idioms, patterns .935 Basic complexity hiding . 935 Factories: encapsulating object creation .935 Polymorphic factories .938 Abstract factories 941 Virtual constructors 943 Callbacks 949 Functor/Command 949 Strategy . 949 Observer .949 Multiple dispatching 959 Visitor, a type of multiple dispatching962 Efficiency . 966 Flyweight 966 The composite 966 Evolving a design: the trash recycler .966 Improving the design . 971 “Make more objects” 971 A pattern for prototyping creation 976 Abstracting usage .987 Applying double dispatching . 992 Implementing the double dispatch 992 Applying the visitor pattern . 997 RTTI considered harmful? .1003 Summary 1006 Exercises 1007 [...]... "Thinking in C++" All rights reserved EXCEPT as allowed by the following statements: You can freely use this file for your own work (personal or commercial), including modifications and distribution in executable form only Permission is granted to use this file in classroom situations, including its use in presentation materials, as long as the book "Thinking in C++" is cited as the source Except in. .. ended up learning by experiment and iteration (a technique that also works well in C++ program design) Eventually I developed a course using everything I had learned from my teaching experience, one I would be happy giving for a long time It tackles the learning 1 Bjarne Stroustrup, The C++ Programming Language, Addison-Wesley, 1986 (first edition) 2 Using C++, ibid 3 Using C++ and C++ Inside & Out,... rapid introduction to C, assuming that you have some kind of programming experience already In addition, just as you learn many new words intuitively by seeing them in context in a novel, it’s possible to learn a great deal about C from the context in which it is used in the rest of the book Thinking in C For those of you who need a gentler introduction to C than the chapter in this book, I have created... experience in some programming language, although not necessarily C If you feel you need more preparation in programming and the syntax of C before tackling this book, you may want to consider MindView’s Thinking in C: Foundations for C++ and Java” training CD ROM, available at http://www.MindView.net This chapter is background and supplementary material Many people do not feel comfortable wading into object-oriented... to you the insights which have rearranged my brain to make me start thinking in C++. ” Prerequisites In the first edition of this book, I decided to assume that someone else had taught you C and that you have at least a reading level of comfort with it My primary focus was on simplifying what I found difficult – the C++ language In this edition I have added a chapter that is a very rapid introduction... and volatile keywords that have additional meaning in C++, especially inside classes It also shows how the meaning of const varies inside and outside classes and how to create compile-time constants in classes (7) Inline functions Preprocessor macros eliminate function call overhead, but the preprocessor also eliminates valuable C++ type checking The inline function gives you all the benefits of a preprocessor... if you are thinking about design, not simply coding And to understand C++ in this way, you must understand the problems with C and with programming in general This book discusses programming problems, why they are problems, and the approach C++ has taken to solve such problems Thus, the set of features I explain in each chapter will be based on the way I see a particular type of problem being solved... 1: Introduction to objects The genesis of the computer revolution was in a machine The genesis of our programming languages thus tends to look like that machine But computers are not so much machines as they are mind amplification tools (“bicycles for the mind,” as Steve Jobs is fond of saying) and a different kind of expressive medium As a result, the tools are beginning to look less like machines... Teaching C++ has become my profession; I’ve seen nodding heads, blank faces, and puzzled expressions in audiences all over the world since 1989 As I began giving in- house training with smaller groups of people, I discovered something during the exercises Even those people who were smiling and nodding were confused about many issues I found out, by chairing the C++ track at the Software Development Conference... my own This resulted in my first C++ book,2 which was essentially a brain dump of my experience That was designed as a reader’s guide, to bring programmers into C and C++ at the same time Both editions3 of the book garnered an enthusiastic response and I still feel it is a valuable resource At about the same time that Using C++ came out, I began teaching the language Teaching C++ has become my profession; . Strings 519 What’s in a string 519 Creating and initializing C++ strings521 Operating on strings .523 Appending, inserting. C++ Programming Language , Addison-Wesley, 1986 (first edition) . 2 Using C++ , ibid. 3 Using C++ and C++ Inside & Out , ibid. Preface 19 problem in

Ngày đăng: 22/12/2013, 00:17

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan