professional c++ programming (programmer to programmer)

865 2.6K 0
professional c++ programming (programmer to programmer)

Đ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

TeA M YYe PG Digitally signed by TeAM YYePG DN: cn=TeAM YYePG, c=US, o=TeAM YYePG, ou=TeAM YYePG, email=yyepg@ms n.com Reason: I attest to the accuracy and integrity of this document Date: 2005.02.23 21:59:53 +08'00' Professional C++ Nicholas A. Solter Scott J. Kleper 01_574841 ffirs.qxd 12/15/04 3:38 PM Page i Professional C++ Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2005 by Wiley Publishing, Inc. All rights reserved. Published simultaneously in Canada Printed in the United States of America 10 9 8 7 6 5 4 3 2 1 1B/QV/QR/QV/IN 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, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, e-mail: brandreview@wiley.com. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CRE- ATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CON- TAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOT THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEB SITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FUR- THER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFOR- MATION THE ORGANIZATION OR WEB SITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ. For general information on our other products and services please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Trademarks: Wiley, the Wiley Publishing logo, Wrox, the Wrox logo, Programmer to Programmer and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. Solter, Nicholas, 1977- Professional C++ / Nicholas Solter, Scott Kleper. p. cm. Includes index. ISBN 0-7645-7484-1 (paper/website) 1. C++ (Computer program language) I. Kleper, Scott, 1977- II. Title. QA76.73.C153S665 2005 005.13'3 dc22 2004027959 01_574841 ffirs.qxd 12/15/04 3:38 PM Page ii Dedications To Sonja, for her unconditional love and support, and to my son Kai, whose frequent interruptions reminded me what’s important in life. —Nicholas A. Solter To Marni, whose unpredictable cuteness brightens every day. —Scott J. Kleper Acknowledgments We owe a debt of gratitude to the many people who have made this book possible. We’d like to thank David Fugate of Waterside Productions for all of his advice and guidance, and Robert Elliot at Wiley for giving two unknown authors the opportunity to tell the C++ story in a new way. This book would not have turned out nearly as well as it did without the assistance of our development editor, Adaobi Obi Tulton. Thanks also to Kathryn Malm Bourgoine for her editorial assistance. The photo on the cover, which artfully minimized our nerdiness, was taken by Adam Tow. We also want to thank all of the coworkers and teachers who have encouraged us to code the right way over the years. In particular, thanks to Mike Hanson, Maggie Johnson, Adam Nash, Nick Parlante, Bob Plummer, Eric Roberts, Mehran Sahami, Bill Walker, Dan Walkowski, Patrick Young, and Julie Zelenski. Our eternal thanks to Jerry Cain, who not only taught us C++ originally, but also served as technical edi- tor, religiously analyzing the code in this book as though it were one of our final exams. Thanks also to the following people, who reviewed one or more chapters: Rob Baesman, Aaron Bradley, Elaine Cheung, Marni Kleper, Toli Kuznets, Akshay Rangnekar, Eltefaat Shokri, Aletha Solter, Ken Solter, and Sonja Solter. Any remaining errors are, of course, our own. We’d like to thank our families for their patience and support. Finally, we’d like to thank you, our readers, for trying out our approach to professional C++ development. 01_574841 ffirs.qxd 12/15/04 3:38 PM Page iii Credits Vice President and Executive Group Publisher Richard Swadley Vice President and Publisher Joseph B. Wikert Executive Editor Robert Elliott Editorial Manager Kathryn Malm Bourgoine Senior Production Editor Geraldine Fahey Senior Development Editor Adaobi Obi Tulton Production Editor Felicia Robinson Media Development Specialist Richard Graves Technical Editor Jerry Cain Text Design & Composition Wiley Composition Services Cover Photographer Adam Tow Author Bios Nicholas A. Solter studied computer science at Stanford University, where he earned bachelor of science and master of science degrees, with a concentration in systems. While a student, he worked as a teaching assistant for several classes ranging from introductory computer science for nonmajors to an upper- division course on group projects and software engineering. Now a software engineer at Sun Microsystems, Nick programs primarily in C and C++ in his work on high-availability software. His previous work experience includes several stints in the computer game industry. At Digital Media International, he was the lead programmer on the multimedia educational game, The Land Before Time Math Adventure. During an internship at Electronic Arts, he helped develop the Course Architect 2000 golf course–editing tool for the Tiger Woods PGA Tour 2000 game. In addition to his industry experience, Nick taught C++ for one year as an adjunct professor of computer science at Fullerton College. When not working, Nick enjoys reading, playing basketball, taking care of his son Kai, and spending time with his family. Scott J. Kleper began his programming career in elementary school, writing adventure games in BASIC for the Tandy TRS-80. As the resident Mac geek at his high school, Scott moved to higher-level languages and released several award-winning shareware applications. Scott attended Stanford University, where he obtained bachelor of science and master of science degrees in computer science, with a concentration in human-computer interaction. While in college, Scott served as a teaching assistant for classes involving introductory programming, object-oriented design, data structures, GUI frameworks, group projects, and Internet programming. Since graduating, Scott has served as a lead engineer on the founding teams of several companies and is currently a senior software engineer at Reactivity, Inc. Outside of work, Scott is a compulsive online shopper, an avid reader, and an awful guitarist. 01_574841 ffirs.qxd 12/15/04 3:38 PM Page iv Contents Introduction xxi Who This Book Is For xxi What This Book Covers xxi How This Book Is Structured xxii What You Need to Use This Book xxiii Conventions xxiii Source Code xxiv Errata xxiv p2p.wrox.com xxiv Part I: Introduction to Professional C++ Chapter 1: A Crash Course in C++ 1 The Basics of C++ 1 The Obligatory Hello, World 2 Namespaces 4 Variables 6 Operators 8 Types 10 Conditionals 12 Loops 14 Arrays 15 Functions 16 Those Are the Basics 17 Diving Deeper into C++ 18 Pointers and Dynamic Memory 18 Strings in C++ 21 References 23 Exceptions 23 The Many Uses of const 25 C++ as an Object-Oriented Language 26 Declaring a Class 26 Your First Useful C++ Program 29 An Employee Records System 29 The Employee Class 29 02_574841 ftoc.qxd 12/15/04 3:39 PM Page v vi Contents The Database Class 34 The User Interface 38 Evaluating the Program 41 Summary 41 Chapter 2: Designing Professional C++ Programs 43 What Is Programming Design? 44 The Importance of Programming Design 44 What’s Different about C++ Design? 46 Two Rules for C++ Design 47 Abstraction 47 Reuse 49 Designing a Chess Program 50 Requirements 51 Design Steps 51 Summary 56 Chapter 3: Designing with Objects 57 An Object-Oriented View of the World 57 Am I Thinking Procedurally? 57 The Object-Oriented Philosophy 58 Living in a World of Objects 61 Object Relationships 63 Abstraction 73 Summary 76 Chapter 4: Designing with Libraries and Patterns 77 Reusing Code 77 A Note on Terminology 78 Deciding Whether or Not to Reuse Code 78 Strategies for Reusing Code 81 Bundling Third-Party Applications 85 Open-Source Libraries 86 The C++ Standard Library 87 Designing with Patterns and Techniques 101 Design Techniques 101 Design Patterns 102 Summary 103 02_574841 ftoc.qxd 12/15/04 3:39 PM Page vi vii Contents Chapter 5: Designing for Reuse 105 The Reuse Philosophy 106 How to Design Reusable Code 106 Use Abstraction 107 Structure Your Code for Optimal Reuse 108 Design Usable Interfaces 112 Reconciling Generality and Ease of Use 117 Summary 118 Chapter 6: Maximizing Software-Engineering Methods 119 The Need for Process 119 Software Life-Cycle Models 120 The Stagewise and Waterfall Models 121 The Spiral Method 123 The Rational Unified Process 126 Software-Engineering Methodologies 127 Extreme Programming (XP) 128 Software Triage 132 Building Your Own Process and Methodology 132 Be Open to New Ideas 132 Bring New Ideas to the Table 132 Recognize What Works and What Doesn’t Work 133 Don’t Be a Renegade 133 Summary 133 Part II: C++ Coding the Professional Way Chapter 7: Coding with Style 135 The Importance of Looking Good 135 Thinking Ahead 135 Keeping It Clear 136 Elements of Good Style 136 Documenting Your Code 136 Reasons to Write Comments 136 Commenting Styles 140 Comments in This Book 145 02_574841 ftoc.qxd 12/15/04 3:39 PM Page vii viii Contents Decomposition 145 Decomposition through Refactoring 147 Decomposition by Design 147 Decomposition in This Book 148 Naming 148 Choosing a Good Name 148 Naming Conventions 148 Using Language Features with Style 151 Use Constants 151 Take Advantage of const Variables 151 Use References Instead of Pointers 151 Use Custom Exceptions 152 Formatting 152 The Curly Brace Alignment Debate 153 Coming to Blows over Spaces and Parentheses 154 Spaces and Tabs 154 Stylistic Challenges 155 Summary 155 Chapter 8: Gaining Proficiency with Classes and Objects 157 Introducing the Spreadsheet Example 157 Writing Classes 158 Class Definitions 158 Defining Methods 161 Using Objects 164 Object Life Cycles 165 Object Creation 165 Object Destruction 176 Assigning to Objects 177 Distinguishing Copying from Assignment 180 Summary 182 Chapter 9: Mastering Classes and Objects 183 Dynamic Memory Allocation in Objects 183 The Spreadsheet Class 184 Freeing Memory with Destructors 186 Handling Copying and Assignment 186 Different Kinds of Data Members 194 Static Data Members 195 Const Data Members 196 Reference Data Members 198 Const Reference Data Members 199 02_574841 ftoc.qxd 12/15/04 3:39 PM Page viii ix Contents More about Methods 199 Static Methods 199 Const Methods 200 Method Overloading 202 Default Parameters 203 Inline Methods 204 Nested Classes 206 Friends 208 Operator Overloading 209 Implementing Addition 209 Overloading Arithmetic Operators 212 Overloading Comparison Operators 215 Building Types with Operator Overloading 216 Pointers to Methods and Members 217 Building Abstract Classes 218 Using Interface and Implementation Classes 218 Summary 221 Chapter 10: Discovering Inheritance Techniques 223 Building Classes with Inheritance 224 Extending Classes 224 Overriding Methods 227 Inheritance for Reuse 230 The WeatherPrediction Class 230 Adding Functionality in a Subclass 231 Replacing Functionality in a Subclass 233 Respect Your Parents 234 Parent Constructors 234 Parent Destructors 235 Referring to Parent Data 237 Casting Up and Down 239 Inheritance for Polymorphism 240 Return of the Spreadsheet 240 Designing the Polymorphic Spreadsheet Cell 241 The Spreadsheet Cell Base Class 242 The Individual Subclasses 243 Leveraging Polymorphism 245 Future Considerations 246 Multiple Inheritance 248 Inheriting from Multiple Classes 248 Naming Collisions and Ambiguous Base Classes 249 02_574841 ftoc.qxd 12/15/04 3:39 PM Page ix [...]... Allocation Errors Errors in Constructors Errors in Destructors Putting It All Together Summary 424 424 427 428 428 430 Part IV: Ensuring Bug-Free Code Chapter 16: Overloading C++ Operators Overview of Operator Overloading 431 432 Why Overload Operators? Limitations to Operator Overloading Choices in Operator Overloading Operators You Shouldn’t Overload Summary of Overloadable Operators 432 432 433 435 435 Overloading... organizations today Part II, “Coding C++ the Professional Way,” provides a technical tour of C++ from the Professional point-of-view You will read about how to write readable C++ code, how to create reusable classes, and how to leverage important language features like inheritance and templates Part III, “Mastering Advanced Features of C++, ” demonstrates how you can get the most out of C++ This part of the book... of C++ to cover lesser-known and often misunderstood language features You will gain an appreciation for object-oriented design and acquire top-notch debugging skills Perhaps most importantly, you will finish this book armed with a wealth of reusable ideas that can be applied to your actual daily work There are many good reasons to make the effort to be a professional C++ programmer, as opposed to. .. You don’t need to know about object-oriented programming just yet—that is covered in Chapter 3 You will also need to be familiar with the compiler you will be using to develop your code This book does not provide directions for using individual compilers Refer to the documentation that came with your compiler for a refresher What This Book Covers Professional C++ is an approach to C++ programming that... one ternary operator in C++ and it is covered in the next section, “Conditionals.” Operator Usage = Binary operator to assign the value on the right to the variable on the left int i = int j = ! Unary operator to negate the true/false (non-0/0) status of a variable bool b = !true; bool b2 = !b; + Binary operator for addition int i = 3 + 2; int j = i + 5; int k = i + j; * / Binary operators for subtraction,... Implementing operator-> What in the World Is operator->* ? Writing Conversion Operators Ambiguity Problems with Conversion Operators Conversions for Boolean Expressions 438 439 441 441 443 446 447 448 449 451 452 452 453 454 455 Overloading the Memory Allocation and Deallocation Operators 457 How new and delete Really Work Overloading operator new and operator delete Overloading operator new and operator delete... quality of your code and improve your programming efficiency Professional C++ teaches more than just the syntax and language features of C++ It also emphasizes programming methodologies, reusable design patterns, and good xxi Introduction programming style The Professional C++ methodology incorporates the entire software development process—from designing and writing code to testing, debugging, and working... hallmarks of good programming Professional C++ programmers understand the correct way to use the language, in addition to the syntax They recognize the importance of good design, the theories of object-oriented programming, and the best ways to use existing libraries They have also developed an arsenal of useful code and reusable ideas By reading this book, you will become a professional C++ programmer... years, C++ has served as the de facto language for writing fast, powerful, and enterprise-class object-oriented programs As popular as C++ has become, the language is surprisingly difficult to grasp in full There are simple, but powerful, techniques that professional C++ programmers use that don’t show up in traditional texts, and there are useful parts of C++ that remain a mystery even to experienced C++. .. “Introduction to Professional C++ Design,” begins with a crash course in C++ basics to ensure a foundation of C++ knowledge Following the crash course, Part I explores C++ design methodologies You will read about the importance of design, the object-oriented methodology, the use of libraries and patterns, the importance of code reuse, and the engineering practices being used by programming organizations today . 16: Overloading C++ Operators 431 Overview of Operator Overloading 432 Why Overload Operators? 432 Limitations to Operator Overloading 432 Choices in Operator Overloading 433 Operators You Shouldn’t. Wikert Executive Editor Robert Elliott Editorial Manager Kathryn Malm Bourgoine Senior Production Editor Geraldine Fahey Senior Development Editor Adaobi Obi Tulton Production Editor Felicia Robinson Media. You Need to Use This Book xxiii Conventions xxiii Source Code xxiv Errata xxiv p2p.wrox.com xxiv Part I: Introduction to Professional C++ Chapter 1: A Crash Course in C++ 1 The Basics of C++ 1 The

Ngày đăng: 01/06/2014, 12:24

Từ khóa liên quan

Mục lục

  • 000866.pdf

  • 000867.pdf

  • 000868.pdf

  • 000869.pdf

  • 000870.pdf

  • 000871.pdf

  • 000872.pdf

  • 000873.pdf

  • 000874.pdf

  • 000875.pdf

  • 000876.pdf

  • 000877.pdf

  • 000878.pdf

  • 000879.pdf

  • 000880.pdf

  • 000881.pdf

  • 000882.pdf

  • 000883.pdf

  • 000884.pdf

  • 000885.pdf

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

Tài liệu liên quan