Object oriented programming in c++r

1K 97 0
Object oriented programming in c++r

Đ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

This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Waite Group's Object-Oriented Programming in C++, Third Edition (Publisher: Macmillan Computer Publishing) Author(s): Robert Lafore ISBN: 157169160x Publication Date: 11/25/98 Previous Table of Contents Next Introduction Object-Oriented Programming (OOP) is the most dramatic innovation in software development in the last decade It ranks in importance with the development of the first higher-level languages at the dawn of the computer age Sooner or later, every programmer will be affected by the objectoriented approach to program design Advantages of OOP Why is everyone so excited about OOP? The chief problem with computer programs is complexity Large programs are probably the most complicated entities ever created by humans Because of this complexity, programs are prone to error, and software errors can be expensive and even life threatening (in air-traffic control, for example) Object-Oriented Programming offers a new and powerful way to cope with this complexity Its goal is clearer, more reliable, more easily maintained programs Languages and Development Platforms Of the Object-Oriented Programming languages, C++ is by far the most widely used (Java, a recent addition to the field of OO languages, lacks certain features, such as pointers, that make it less powerful and versatile than C++.) In past years the standards for C++ have been in a state of evolution This meant that each compiler vendor handled certain details differently However, in November 1997, the ANSI/ISO C++ standards committee approved the final draft of what is now known as Standard C++ (ANSI stands for American National Standards Institute, and ISO stands for International Standards Institute.) Standard C++ adds many new features to the language, such as the Standard Template Library (STL) In this book we follow Standard C++ (except for a few places which we’ll note as we go along) The most popular development environments for C++ are manufactured by Microsoft and Borland and run on the various flavors of Microsoft Windows In this book we’ve attempted in ensure that all example programs run on the current versions of both Borland and Microsoft compilers (See Appendixes C and D for more on these compilers.) What this Book Does This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com This book teaches Object-Oriented Programming with the C++ programming language, using either Microsoft or Borland compilers It is suitable for professional programmers, students, and kitchentable enthusiasts New Concepts OOP involves concepts that are new to programmers of traditional languages such as Pascal, Basic, and C These ideas, such as classes, inheritance, and polymorphism, lie at the heart of ObjectOriented Programming But it’s easy to lose sight of these concepts when discussing the specifics of an object-oriented language Many books overwhelm the reader with the details of language features, while ignoring the reason these features exist This book attempts to keep an eye on the big picture and relate the details to the larger concepts The Gradual Approach We take a gradual approach in this book, starting with very simple programming examples and working up to full-fledged object-oriented applications We introduce new concepts slowly so that you will have time to digest one idea before going on to the next We use figures whenever possible to help clarify new ideas There are questions and programming exercises at the end of most chapters to enhance the book’s usefulness in the classroom Answers to the questions and to the first few (starred) exercises can be found in Appendix D The exercises vary in difficulty to pose a variety of challenges for the student What You Need to Know to Use this Book You can use this book even if you have no previous programming experience However, such experience, in BASIC or Pascal, for example, certainly won’t hurt You not need to know the C language to use this book Many books on C++ assume that you already know C, but this one does not It teaches C++ from the ground up If you know C, it won’t hurt, but you may be surprised at how little overlap there is between C and C++ You should be familiar with the basic operations of Microsoft Windows, such as starting applications and copying files Software and Hardware You should have the latest version of either the Microsoft or the Borland C++ compiler Both products come in low-priced “Learning Editions” suitable for students Appendix C provides detailed information on operating the Microsoft compiler, while Appendix D does the same for the Inprise (Borland) product Other compilers will probably handle most of the programs in this book as written, if they adhere to Standard C++ Your computer should have enough processor speed, memory, and hard disk space to run the compiler you’ve chosen You can check the manufacturer’s specifications to determine these requirements Console-Mode Programs This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com The example programs in this book are console-mode programs They run in a character-mode window within the compiler environment, or directly within an MS-DOS box This avoids the complexity of full-scale graphics-oriented Windows programs Go for It! You may have heard that C++ is difficult to learn It’s true that it might be a little more challenging than BASIC, but it’s really quite similar to other languages, with two or three “grand ideas” thrown in These new ideas are fascinating in themselves, and we think you’ll have fun learning about them They are also becoming part of the programming culture; they’re something everyone should know a little bit about, like evolution and psychoanalysis We hope this book will help you enjoy learning about these new ideas, at the same time that it teaches you the details of programming in C++ A Note to Teachers Teachers, and others who already know C, may be interested in some details of the approach we use in this book and how it’s organized Standard C++ We’ve revised all the programs in this book to make them compatible with Standard C++ This involved, at a minimum, changes to header files, the addition of namespace designation, and making return type Many programs received more extensive modifications, including the substitution in many places of the new class for the old C-style strings We devote a new chapter to the STL (Standard Template Library), which is now included in Standard C++ Object-Oriented Design Students are frequently mystified by the process of breaking a programming project into appropriate classes For this reason we’ve added a chapter on object-oriented design This chapter is placed near the end of the book, but we encourage students to skim it earlier to get the flavor of OOD Of course, small programs don’t require such a formal design approach, but it’s helpful to know what’s involved even when designing programs in your head C++ is not the same as C Some institutions want their students to learn C before learning C++ In our view this is a mistake C and C++ are entirely separate languages It’s true that their syntax is similar, and C is actually a subset of C++ But the similarity is largely a historical accident In fact, the basic approach in a C program is radically different from that in a C program C++ has overtaken C as the preferred language for serious software development Thus we don’t believe it is necessary or advantageous to teach C before teaching C++ Students who don’t know C are saved the time and trouble of learning C and then learning C++, an inefficient approach Students who already know C may be able to skim parts of some chapters, but they will find that a remarkable percentage of the material is new Optimize Organization for OOP We could have begun the book by teaching the procedural concepts common to C and C++, and This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com We could have begun the book by teaching the procedural concepts common to C and C++, and moved on to the new OOP concepts once the procedural approach had been digested That seemed counterproductive, however, because one of our goals is to begin true Object-Oriented Programming as quickly as possible Accordingly, we provide a minimum of procedural groundwork before getting to objects in Chapter Even the initial chapters are heavily steeped in C++, as opposed to C, usage We introduce some concepts earlier than is traditional in books on C For example, structures are a key feature for understanding C++ because classes are syntactically an extension of structures For this reason, we introduce structures in Chapter so that they will be familiar when we discuss classes Some concepts, such as pointers, are introduced later than in traditional C books It’s not necessary to understand pointers to follow the essentials of OOP, and pointers are usually a stumbling block for C and C++ students Therefore, we defer a discussion of pointers until the main concepts of OOP have been thoroughly digested Substitute Superior C++ Features Some features of C have been superseded by new approaches in C++ For instance, the and functions, input/output workhorses in C, are seldom used in C++ because and a better job Consequently, we leave out descriptions of these functions Similarly, constants and macros in C have been largely superseded by the qualifier and inline functions in C++, and need be mentioned only briefly Minimize Irrelevant Capabilities Because the focus in this book is on Object-Oriented Programming, we can leave out some features of C that are seldom used and are not particularly relevant to OOP For instance, it isn’t necessary to understand the C bit-wise operators (used to operate on individual bits) to learn Object-Oriented Programming These and a few other features can be dropped from our discussion, or mentioned only briefly, with no loss in understanding of the major features of C++ The result is a book that focuses on the fundamentals of OOP, moving the reader gently but briskly toward an understanding of new concepts and their application to real programming problems Programming Examples There are numerous listings of code scattered throughout the book that you will want to try out for yourself The program examples are available for download by going to Macmillan Computer Publishing’s web site, http://www.mcp.com/product_support, and go to this book’s page by entering the ISBN and clicking Search To download the programming examples, just click the appropriate link on the page Programming Exercises One of the major changes in the second edition was the addition of numerous exercises Each of these involves the creation of a complete C++ program There are roughly 12 exercises per chapter This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com these involves the creation of a complete C++ program There are roughly 12 exercises per chapter Solutions to the first three or four exercises in each chapter are provided in Appendix D For the remainder of the exercises, readers are on their own, although qualified instructors can suggested solutions Please visit Macmillan Computer Publishing’s Web site, http://www.mcp.com/product_support, and go to this book’s page by entering the ISBN and clicking Search Click on the appropriate link to receive instructions on downloading the encrypted files and decoding them The exercises vary considerably in their degree of difficulty In each chapter the early exercises are fairly easy, while later ones are more challenging Instructors will probably want to assign only those exercises suited to the level of a particular class Previous Table of Contents Next This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Waite Group's Object-Oriented Programming in C++, Third Edition (Publisher: Macmillan Computer Publishing) Author(s): Robert Lafore ISBN: 157169160x Publication Date: 11/25/98 Previous Table of Contents Next Preface The major changes to this Third Edition are concerned with Standard C++ and object-oriented design In addition, the book is no longer geared exclusively to Borland C++ compilers Standard C++, finalized in the fall of 1997, introduced many new features to C++ Some of these features, such as templates and exceptions, had already been adopted by compiler manufacturers However, the Standard Template Library (STL) has only recently been included in compilers This book adds a chapter on the STL We’ve also introduced other features from Standard C++, including new header files, the string class, new-style casts, namespaces, and so on The design of object-oriented programs has received increasing emphasis in recent years, so we’ve added a chapter on object-oriented design The advent of Standard C++ means that, at least to a greater extent than before, all compilers should treat source code in the same way Accordingly, we’ve modified our emphasis on Borland compilers, and now focus on code that should work with any Standard C++ compiler Of course, the reality seldom matches the ideal, so so the programs in this book have been tested with both Microsoft and Borland compilers, and modified when necessary to work with both of them Previous Table of Contents Next This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Waite Group's Object-Oriented Programming in C++, Third Edition (Publisher: Macmillan Computer Publishing) Author(s): Robert Lafore ISBN: 157169160x Publication Date: 11/25/98 Previous Table of Contents Next About the Author Robert Lafore has been writing books about computer programming since 1982 His best-selling titles include Assembly Language Programming for the IBM PC, C Programming Using Turbo C++, C++ Interactive Course, and Data Structures and Algorithms in Java Mr Lafore holds degrees in mathematics and electrical engineering, and has been active in programming since the days of the PDP-5, when 4K of main memory was considered luxurious His interests include hiking, windsurfing, and recreational mathematics Acknowledgments to the Third Edition I’d like to thank the entire team at Macmillan Computer Publishing In particular, Tracy Dunkelberger ably spearheaded the entire project and exhibited great patience with what turned out to be a lengthy schedule Jeff Durham handled the myriad details involved in interfacing between me and the editors with skill and good humor Andrei Kossorouko lent his expertise in C++ to ensure that I didn’t make this edition worse instead of better Acknowledgments to the Second Edition My thanks to the following professor—susers of this book as a text at their respective colleges and universities—for their help in planning the second edition: Dave Bridges, Frank Cioch, Jack Davidson, Terrence Fries, Jimmie Hattemer, Jack Van Luik, Kieran Mathieson, Bill McCarty, Anita Millspaugh, Ian Moraes, Jorge Prendes, Steve Silva, and Edward Wright I would like to thank the many readers of the first edition who wrote in with corrections and suggestions, many of which were invaluable At Waite Group Press, Joanne Miller has ably ridden herd on my errant scheduling and filled in as academic liaison, and Scott Calamar, as always, has made sure that everyone knew what they were doing Deirdre Greene provided an uncannily sharp eye as copy editor Thanks, too, to Mike Radtke and Harry Henderson for their expert technical reviews Special thanks to Edward Wright, of Western Oregon State College, for reviewing and experimenting with the new exercises Acknowledgments to the First Edition This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com My primary thanks go to Mitch Waite, who poured over every inch of the manuscript with painstaking attention to detail and made a semi-infinite number of helpful suggestions Bill McCarty of Azusa Pacific University reviewed the content of the manuscript and its suitability for classroom use, suggested many excellent improvements, and attempted to correct my dyslexic spelling George Leach ran all the programs, and, to our horror, found several that didn’t perform correctly in certain circumstances I trust these problems have all been fixed; if not, the fault is entirely mine Scott Calamar of The Waite Group dealt with the myriad organizational aspects of writing and producing this book His competence and unfailing good humor were an important ingredient in its completion I would also like to thank Nan Borreson of Borland for supplying the latest releases of the software (among other useful tidbits), Harry Henderson for reviewing the exercises, Louise Orlando of The Waite Group for ably shepherding the book through production, Merrill Peterson of Matrix Productions for coordinating the most trouble-free production run I’ve ever been involved with, Juan Vargas for the innovative design, and Frances Hasegawa for her uncanny ability to decipher my sketches and produce beautiful and effective art Dedication This book is dedicated to GGL another inodomitable spirit.222 Tell Us What You Think! As the reader of this book, you are our most important critic and commentator We value your opinion and want to know what we’re doing right, what we could better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way As the Executive Editor for the Advanced Programming and Distributed Architectures team at Macmillan Computer Publishing, I welcome your comments You can fax, email, or write me directly to let me know what you did or didn’t like about this book—as well as what we can to make our books stronger Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message When you write, please be sure to include this book’s title and author as well as your name and phone or fax number I will carefully review your comments and share them with the author and editors who worked on the book Fax: 317-817-7070 Email: programming@mcp.com Mail: Tracy Dunkelberger Executive Editor Advanced Programming and Distributed Architectures Macmillan Computer Publishing This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com 201 West 103rd Street Indianapolis, IN 46290 USA Previous Table of Contents Next This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Waite Group's Object-Oriented Programming in C++, Third Edition (Publisher: Macmillan Computer Publishing) Author(s): Robert Lafore ISBN: 157169160x Publication Date: 11/25/98 Previous Table of Contents Next APPENDIX A ASCII Chart Table A.1 IBM Character Codes DEC HEX Symbol 00 (NULL) A 01 B 02 C 03 D 04 E 05 F 06 G 07 H 08 I 09 J 10 0A K 11 0B L 12 0C M 13 0D N 14 0E O 15 0F P 16 10 Q 17 11 R 18 12 S 19 13 T 20 14 U 21 15 _ 22 16 W 23 17 X 24 18 Y 25 19 Z 26 1A a 27 1B b 28 1C Key Ctrl Ctr A Ctrl B Ctrl C Ctrl B Ctrl E Ctrl F Ctrl G Backspace Tab Ctrl J Ctrl K Ctrl L Enter Ctrl N Ctrl O Ctrl P Ctrl Q Ctrl R Ctrl S Ctrl T Ctrl U Ctrl V Ctrl W Ctrl X Ctrl Y Ctrl Z Escape Ctrl \ Use in C Beep Backspace Tab Linefeed (new line) Vertical Tab Form Feed Carriage Return This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Overloading Binary Operators Arithmetic Operators Concatenating Strings Multiple Overloading Comparison Operators Arithmetic Assignment Operators The Subscript Operator [ ] Data Conversion Conversions Between Basic Types Conversions Between Objects and Basic Types Conversions Between Objects of Different Classes Conversions: When to Use What Pitfalls of Operator Overloading and Conversion Use Similar Meanings Use Similar Syntax Show Restraint Avoid Ambiguity Not All Operators Can Be Overloaded Keywords explicit and mutable Preventing Conversions with explicit Changing const Object Data Using mutable Summary Questions Exercises CHAPTER 9—INHERITANCE Derived Class and Base Class Specifying the Derived Class Accessing Base Class Members The protected Access Specifier Derived Class Constructors Overriding Member Functions Which Function Is Used? Scope Resolution with Overridden Functions Inheritance in the English Distance Class Operation of ENGLEN Constructors in DistSign Member Functions in DistSign This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Abetting Inheritance Class Hierarchies “Abstract” Base Class Constructors and Member Functions Inheritance and Graphics Shapes Public and Private Inheritance Access Combinations Access Specifiers: When to Use What Levels of Inheritance Multiple Inheritance Member Functions in Multiple Inheritance private Derivation in EMPMULT Constructors in Multiple Inheritance Ambiguity in Multiple Inheritance Containership: Classes Within Classes Inheritance and Program Development Summary Questions Exercises CHAPTER 10—POINTERS Addresses and Pointers The Address-of Operator & Pointer Variables Syntax Quibbles Accessing the Variable Pointed To Pointer to void Pointers and Arrays Pointer Constants and Pointer Variables Pointers and Functions Passing Simple Variables Passing Arrays Sorting Array Elements Pointers and C-type Strings This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Pointers and C-type Strings Pointers to String Constants Strings As Function Arguments Copying a String Using Pointers Library String Functions The const Modifier and Pointers Arrays of Pointers to Strings Memory Management: new and delete The new Operator The delete Operator A String Class Using new Pointers to Objects Referring to Members Another Approach to new An Array of Pointers to Objects A Linked List Example A Chain of Pointers Adding an Item to the List Displaying the List Contents Self-Containing Classes Augmenting linklist Pointers to Pointers Sorting Pointers The person** Data Type Comparing Strings A Parsing Example Parsing Arithmetic Expressions The PARSE Program Simulation: A HORSE Race Debugging Pointers Summary Questions Exercises CHAPTER 11—VIRTUAL FUNCTIONS Finding An object’s class with TYPEID( )11 Virtual Functions Normal Member Functions Accessed with Pointers This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Virtual Member Functions Accessed with Pointers Late Binding Abstract Classes and Pure Virtual Functions Virtual Functions and the person Class Virtual Functions in a Graphics Example Virtual Destructors Virtual Base Classes Friend Functions Friends As Bridges Breaching the Walls English Distance Example friends for Functional Notation friend Classes Static Functions Accessing static Functions Numbering the Objects Investigating Destructors Assignment and Copy Initialization Overloading the Assignment Operator The Copy Constructor A Memory-Efficient String Class The this Pointer Accessing Member Data with this Using this for Returning Values Revised strimem Program Dynamic Type Information Checking the Type of a Class with dynamic_cast Changing Pointer Types with dynamic_cast The typeid Operator Summary Questions Exercises CHAPTER 12—STREAMS AND FILES Stream Classes Advantages of Streams The Stream Class Hierarchy The ios Class This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com The istream Class The ostream Class The iostream and the _withassign Classes Stream Errors Error-Status Bits Inputting Numbers Too Many Characters No-Input Input Inputting Strings and Characters Error-Free Distances Disk File I/O with Streams Formatted File I/O Strings with Embedded Blanks Character I/O Binary I/O The reinterpret_cast Operator Closing Files Object I/O I/O with Multiple Objects File Pointers Specifying the Position Specifying the Offset The tellg() Function Error Handling in File I/O Reacting to Errors Analyzing Errors File I/O with Member Functions Objects That Read and Write Themselves Classes That Read and Write Themselves Overloading the Extraction and Insertion Operators Overloading for cout and cin Overloading for Files Memory As a Stream Object Command-Line Arguments Printer Output Summary Questions Exercises This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com CHAPTER 13—MULTIFILE PROGRAMS Reasons for Multifile Programs Class Libraries Organization and Conceptualization Creating a Multifile Program Header Files Directory Projects A Very Long Number Class Numbers As Strings The Class Specifier The Member Functions The Application Program A High-Rise elevator Simulation Running the ELEV Program Designing the System Listings for ELEV Elevator Strategy A Water-Distribution System Components of a Water System Flow, Pressure, and Back Pressure Component Input and Output Making Connections Simplifying Assumptions Program Design Programming the Connections Base and Derived Classes The Component Base Class The Flows-Into Operator Derived Classes The Switch Class The PIPE_APP.CPP File Summary Questions Projects CHAPTER 14—TEMPLATES AND EXCEPTIONS This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Function Templates A Simple Function Template Function Templates with Multiple Arguments Class Templates Class Name Depends on Context A Linked List Class Using Templates Storing User-Defined Data Types Exceptions Why Do We Need Exceptions? Exception Syntax A Simple Exception Example Multiple Exceptions Exceptions with the Distance Class Exceptions with Arguments Extracting Data from the Exception Object The bad_alloc Class Exception Notes Summary Questions Exercises CHAPTER 15—THE STANDARD TEMPLATE LIBRARY Introduction to the STL Containers Algorithms Iterators Potential Problems with the STL Algorithms The find() Algorithm The count() Algorithm The sort() Algorithm The search() Algorithm The merge() Algorithm Function Objects The for_each() Algorithm The transform() Algorithm Sequential Containers Vectors Lists This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Deques Iterators Iterators as Smart Pointers Iterators as an Interface Matching Algorithms with Containers Iterators at Work Specialized Iterators Iterator Adapters Stream Iterators Associative Containers Sets and Multisets Maps and Multimaps Storing User-Defined Objects A Set of person Objects A List of person Objects Function Objects Predefined Function Objects Writing Your Own Function Objects Function objects Used to Modify Container Behavior Summary Questions Exercises CHAPTER 16—OBJECT-ORIENTED DESIGN Our Approach to OOD CRC Cards Use Cases Class Diagrams The Programming Problem Hand-Written Forms Assumptions The CRC Modeling Team Members of the Team This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com The Problem Summary Statement Constructing the CRC Cards Classes Responsibilities Collaborators The Tenant CRC Card The Expense CRC Card The Rent Input Screen CRC card The Rent Record CRC Card The Expense Input Screen CRC Card he Expense Record CRC Card The Annual Report CRC Card The User Interface CRC Card The Scribe Use Cases Use Case 1: User Inputs an Expense Use Case 2: The User Inputs a Rent Trouble with the “User Inputs a Rent” Use Case The Remaining Use Cases Simplifications Class Relationships Attribute Association Navigability Aggregation Composition Objects and Classes Multiplicity Generalization Coupling and Cohesion Class Diagrams Arranging the CRC Cards Associations in Landlord Aggregations in Landlord Writing the Program The Header file The cpp Files More Simplifications Interacting with the Program Prototyping Final Thoughts This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Summary Questions Projects Appendix A Appendix B Appendix C Appendix D Appendix E Appendix F Appendix G Appendix H Index This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Waite Group's Object-Oriented Programming in C++, Third Edition (Publisher: Macmillan Computer Publishing) Author(s): Robert Lafore ISBN: 157169160x Publication Date: 11/25/98 Previous Table of Contents Next Introduction Object-Oriented Programming (OOP) is the most dramatic innovation in software development in the last decade It ranks in importance with the development of the first higher-level languages at the dawn of the computer age Sooner or later, every programmer will be affected by the objectoriented approach to program design Advantages of OOP Why is everyone so excited about OOP? The chief problem with computer programs is complexity Large programs are probably the most complicated entities ever created by humans Because of this complexity, programs are prone to error, and software errors can be expensive and even life threatening (in air-traffic control, for example) Object-Oriented Programming offers a new and powerful way to cope with this complexity Its goal is clearer, more reliable, more easily maintained programs Languages and Development Platforms Of the Object-Oriented Programming languages, C++ is by far the most widely used (Java, a recent addition to the field of OO languages, lacks certain features, such as pointers, that make it less powerful and versatile than C++.) In past years the standards for C++ have been in a state of evolution This meant that each compiler vendor handled certain details differently However, in November 1997, the ANSI/ISO C++ standards committee approved the final draft of what is now known as Standard C++ (ANSI stands for American National Standards Institute, and ISO stands for International Standards Institute.) Standard C++ adds many new features to the language, such as the Standard Template Library (STL) In this book we follow Standard C++ (except for a few places which we’ll note as we go along) The most popular development environments for C++ are manufactured by Microsoft and Borland and run on the various flavors of Microsoft Windows In this book we’ve attempted in ensure that all example programs run on the current versions of both Borland and Microsoft compilers (See Appendixes C and D for more on these compilers.) What this Book Does This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com This book teaches Object-Oriented Programming with the C++ programming language, using either Microsoft or Borland compilers It is suitable for professional programmers, students, and kitchentable enthusiasts New Concepts OOP involves concepts that are new to programmers of traditional languages such as Pascal, Basic, and C These ideas, such as classes, inheritance, and polymorphism, lie at the heart of ObjectOriented Programming But it’s easy to lose sight of these concepts when discussing the specifics of an object-oriented language Many books overwhelm the reader with the details of language features, while ignoring the reason these features exist This book attempts to keep an eye on the big picture and relate the details to the larger concepts The Gradual Approach We take a gradual approach in this book, starting with very simple programming examples and working up to full-fledged object-oriented applications We introduce new concepts slowly so that you will have time to digest one idea before going on to the next We use figures whenever possible to help clarify new ideas There are questions and programming exercises at the end of most chapters to enhance the book’s usefulness in the classroom Answers to the questions and to the first few (starred) exercises can be found in Appendix D The exercises vary in difficulty to pose a variety of challenges for the student What You Need to Know to Use this Book You can use this book even if you have no previous programming experience However, such experience, in BASIC or Pascal, for example, certainly won’t hurt You not need to know the C language to use this book Many books on C++ assume that you already know C, but this one does not It teaches C++ from the ground up If you know C, it won’t hurt, but you may be surprised at how little overlap there is between C and C++ You should be familiar with the basic operations of Microsoft Windows, such as starting applications and copying files Software and Hardware You should have the latest version of either the Microsoft or the Borland C++ compiler Both products come in low-priced “Learning Editions” suitable for students Appendix C provides detailed information on operating the Microsoft compiler, while Appendix D does the same for the Inprise (Borland) product Other compilers will probably handle most of the programs in this book as written, if they adhere to Standard C++ Your computer should have enough processor speed, memory, and hard disk space to run the compiler you’ve chosen You can check the manufacturer’s specifications to determine these requirements Console-Mode Programs This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com The example programs in this book are console-mode programs They run in a character-mode window within the compiler environment, or directly within an MS-DOS box This avoids the complexity of full-scale graphics-oriented Windows programs Go for It! You may have heard that C++ is difficult to learn It’s true that it might be a little more challenging than BASIC, but it’s really quite similar to other languages, with two or three “grand ideas” thrown in These new ideas are fascinating in themselves, and we think you’ll have fun learning about them They are also becoming part of the programming culture; they’re something everyone should know a little bit about, like evolution and psychoanalysis We hope this book will help you enjoy learning about these new ideas, at the same time that it teaches you the details of programming in C++ A Note to Teachers Teachers, and others who already know C, may be interested in some details of the approach we use in this book and how it’s organized Standard C++ We’ve revised all the programs in this book to make them compatible with Standard C++ This involved, at a minimum, changes to header files, the addition of namespace designation, and making return type Many programs received more extensive modifications, including the substitution in many places of the new class for the old C-style strings We devote a new chapter to the STL (Standard Template Library), which is now included in Standard C++ Object-Oriented Design Students are frequently mystified by the process of breaking a programming project into appropriate classes For this reason we’ve added a chapter on object-oriented design This chapter is placed near the end of the book, but we encourage students to skim it earlier to get the flavor of OOD Of course, small programs don’t require such a formal design approach, but it’s helpful to know what’s involved even when designing programs in your head C++ is not the same as C Some institutions want their students to learn C before learning C++ In our view this is a mistake C and C++ are entirely separate languages It’s true that their syntax is similar, and C is actually a subset of C++ But the similarity is largely a historical accident In fact, the basic approach in a C program is radically different from that in a C program C++ has overtaken C as the preferred language for serious software development Thus we don’t believe it is necessary or advantageous to teach C before teaching C++ Students who don’t know C are saved the time and trouble of learning C and then learning C++, an inefficient approach Students who already know C may be able to skim parts of some chapters, but they will find that a remarkable percentage of the material is new Optimize Organization for OOP We could have begun the book by teaching the procedural concepts common to C and C++, and This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com We could have begun the book by teaching the procedural concepts common to C and C++, and moved on to the new OOP concepts once the procedural approach had been digested That seemed counterproductive, however, because one of our goals is to begin true Object-Oriented Programming as quickly as possible Accordingly, we provide a minimum of procedural groundwork before getting to objects in Chapter Even the initial chapters are heavily steeped in C++, as opposed to C, usage We introduce some concepts earlier than is traditional in books on C For example, structures are a key feature for understanding C++ because classes are syntactically an extension of structures For this reason, we introduce structures in Chapter so that they will be familiar when we discuss classes Some concepts, such as pointers, are introduced later than in traditional C books It’s not necessary to understand pointers to follow the essentials of OOP, and pointers are usually a stumbling block for C and C++ students Therefore, we defer a discussion of pointers until the main concepts of OOP have been thoroughly digested Substitute Superior C++ Features Some features of C have been superseded by new approaches in C++ For instance, the and functions, input/output workhorses in C, are seldom used in C++ because and a better job Consequently, we leave out descriptions of these functions Similarly, constants and macros in C have been largely superseded by the qualifier and inline functions in C++, and need be mentioned only briefly Minimize Irrelevant Capabilities Because the focus in this book is on Object-Oriented Programming, we can leave out some features of C that are seldom used and are not particularly relevant to OOP For instance, it isn’t necessary to understand the C bit-wise operators (used to operate on individual bits) to learn Object-Oriented Programming These and a few other features can be dropped from our discussion, or mentioned only briefly, with no loss in understanding of the major features of C++ The result is a book that focuses on the fundamentals of OOP, moving the reader gently but briskly toward an understanding of new concepts and their application to real programming problems Programming Examples There are numerous listings of code scattered throughout the book that you will want to try out for yourself The program examples are available for download by going to Macmillan Computer Publishing’s web site, http://www.mcp.com/product_support, and go to this book’s page by entering the ISBN and clicking Search To download the programming examples, just click the appropriate link on the page Programming Exercises One of the major changes in the second edition was the addition of numerous exercises Each of these involves the creation of a complete C++ program There are roughly 12 exercises per chapter This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com these involves the creation of a complete C++ program There are roughly 12 exercises per chapter Solutions to the first three or four exercises in each chapter are provided in Appendix D For the remainder of the exercises, readers are on their own, although qualified instructors can suggested solutions Please visit Macmillan Computer Publishing’s Web site, http://www.mcp.com/product_support, and go to this book’s page by entering the ISBN and clicking Search Click on the appropriate link to receive instructions on downloading the encrypted files and decoding them The exercises vary considerably in their degree of difficulty In each chapter the early exercises are fairly easy, while later ones are more challenging Instructors will probably want to assign only those exercises suited to the level of a particular class Previous Table of Contents Next ... Lafore has been writing books about computer programming since 1982 His best-selling titles include Assembly Language Programming for the IBM PC, C Programming Using Turbo C++, C++ Interactive Course,... goals is to begin true Object- Oriented Programming as quickly as possible Accordingly, we provide a minimum of procedural groundwork before getting to objects in Chapter Even the initial chapters... listing, pointing to the opening brace following main If you want to start somewhere other than the beginning of the program, position the cursor on the line where you want to start debugging

Ngày đăng: 26/03/2019, 11:04

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