C -Primer-Plus- (5th-Edition)

C -Primer-Plus- (5th-Edition)

(Parte 1 de 5)

800 East 96th St., Indianapolis, Indiana, 46240 USA

Primer Plus C++

Stephen Prata Fifth Edition

C++ Primer Plus

Copyright © 2005 by Sams Publishing

All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein.

International Standard Book Number: 0-672-32697-3 Library of Congress Catalog Card Number: 2004095067 Printed in the United States of America First Printing: November, 2004 07 06 05 04 4321

Trademarks

All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.

Warning and Disclaimer

Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis.

Bulk Sales

Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact

U.S. Corporate and Government Sales 1-800-382-3419 corpsales@pearsontechgroup.com

For sales outside of the U.S., please contact

International Sales 1-317-428-3341 international@pearsontechgroup.com

ASSOCIATE PUBLISHER Michael Stephens

ACQUISITIONS EDITOR Loretta Yates

DEVELOPMENT EDITOR Songlin Qiu

MANAGING EDITOR Charlotte Clapp

PROJECT EDITOR George E. Nedeff

COPY EDITOR Kitty Jarrett

INDEXER Erika Millen

PROOFREADER Suzanne Thomas

TECHNICAL EDITOR David Horvath

PUBLISHING COORDINATOR Cindy Teeters

MULTIMEDIA DEVELOPER Dan Scherf

BOOK DESIGNER Gary Adair

CHAPTER 1Getting Started1
CHAPTER 2Setting Out to C++29
CHAPTER 3Dealing with Data65
CHAPTER 4Compound Types109
CHAPTER 5Loops and Relational Expressions177
CHAPTER 6Branching Statements and Logical Operators231
CHAPTER 7Functions: C++’s Programming Modules279
CHAPTER 8Adventures in Functions337
CHAPTER 9Memory Models and Namespaces393
CHAPTER 10Objects and Classes445
CHAPTER 11Working with Classes501
CHAPTER 12Classes and Dynamic Memory Allocation561
CHAPTER 13Class Inheritance633
CHAPTER 14Reusing Code in C++701
CHAPTER 15Friends, Exceptions, and More787
CHAPTER 16The stringClass and the Standard Template Library857
CHAPTER 17Input, Output, and Files951
APPENDIX ANumber Bases1041
APPENDIX BC++ Reserved Words1047
APPENDIX CThe ASCII Character Set1051
APPENDIX DOperator Precedence1057
APPENDIX EOther Operators1063
APPENDIX FThe stringTemplate Class1075

INTRODUCTION 1 APPENDIX GThe STL Methods and Functions . . . . . . . . . . . . . . . . . . . . . . .1095

APPENDIX IConverting to ANSI/ISO Standard C++13
APPENDIX JAnswers to Review Questions1141

APPENDIX HSelected Readings and Internet Resources . . . . . . . . . . . . . . . . .1129 INDEX 1165

INTRODUCTION1
CHAPTER 1:Getting Started1
Learning C++: What Lies Before You1
The Origins of C++: A Little History12
The C Language13
C Programming Philosophy13
The C++ Shift: Object-Oriented Programming14
C++ and Generic Programming15
The Genesis of C++16
Portability and Standards17
The Mechanics of Creating a Program19
Creating the Source Code File20
Compilation and Linking2
Summary27
CHAPTER 2:Setting Out to C++29
C++ Initiation29
The main()Function31
C++ Comments34
The C++ Preprocessor and the iostreamFile35
Header Filenames36
Namespaces37
C++ Output with cout38
C++ Source Code Formatting41
C++ Statements43
Declaration Statements and Variables43
Assignment Statements45
A New Trick for cout46
More C++ Statements47
Using cin47
Concatenating with cout48
cinand cout: A Touch of Class48
Functions50
Using a Function That Has a Return Value50
Function Variations54
User-Defined Functions5
Using a User-Defined Function That Has a Return Value58

TABLE OF CONTENTS Placing the usingDirective in Multifunction Programs . . . . . . . . . . . . . . . .60

Review Questions63
Programming Exercises64
CHAPTER 3:Dealing with Data65
Simple Variables6
Names for Variables6
Integer Types68
The short, int, and longInteger Types68
Unsigned Types73
Choosing an Integer Type75
Integer Constants76
How C++ Decides What Type a Constant Is78
The charType: Characters and Small Integers79
The boolType87
The constQualifier8
Floating-Point Numbers89
Writing Floating-Point Numbers89
Floating-Point Types91
Floating-Point Constants93
Advantages and Disadvantages of Floating-Point Numbers94
C++ Arithmetic Operators95
Order of Operation: Operator Precedence and Associativity96
Division Diversions97
The Modulus Operator9
Type Conversions100
Summary105
Review Questions106
Programming Exercises107
CHAPTER 4:Compound Types109
Introducing Arrays110
Program Notes112
Initialization Rules for Arrays113
Strings114
Concatenating String Constants116
Using Strings in an Array116
Adventures in String Input118
Reading String Input a Line at a Time119
Mixing String and Numeric Input124

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .62 viC++ PRIMER PLUS, FIFTH EDITION

Assignment, Concatenation, and Appending126
More stringClass Operations127
More on stringClass I/O129
Introducing Structures131
Using a Structure in a Program133
Can a Structure Use a stringClass Member?135
Other Structure Properties136
Arrays of Structures137
Bit Fields in Structures139
Unions139
Enumerations141
Setting Enumerator Values142
Value Ranges for Enumerations143
Pointers and the Free Store144
Declaring and Initializing Pointers147
Pointer Danger149
Pointers and Numbers150
Allocating Memory with new150
Freeing Memory with delete152
Using newto Create Dynamic Arrays153
Pointers, Arrays, and Pointer Arithmetic156
Program Notes157
Pointers and Strings162
Using newto Create Dynamic Structures166
Automatic Storage, Static Storage, and Dynamic Storage170
Summary172
Review Questions173
Programming Exercises174
CHAPTER 5:Loops and Relational Expressions177
Introducing forLoops178
forLoop Parts179
Back to the forLoop185
Changing the Step Size187
Inside Strings with the forLoop188
The Increment (++) and Decrement (--) Operators189
Side Effects and Sequence Points190
Prefixing Versus Postfixing191
The Increment/Decrement Operators and Pointers191
Combination Assignment Operators192

Introducing the stringClass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .125 viiCONTENTS

The Comma Operator (or More Syntax Tricks)195
Relational Expressions198
A Mistake You’l Probably Make199
Comparing C-Style Strings201
Comparing stringClass Strings204
The whileLoop205
Program Notes207
forVersus while207
Just a Moment—Building a Time-Delay Loop209
The do whileLoop211
Loops and Text Input213
Using Unadorned cinfor Input214
cin.get(char)to the Rescue215
Which cin.get()?216
The End-of-File Condition217
Yet Another Version of cin.get()220
Nested Loops and Two-Dimensional Arrays223
Initializing a Two-Dimensional Array225
Summary227
Review Questions228
Programming Exercises229
CHAPTER 6:Branching Statements and Logical Operators231
The ifStatement231
The if elseStatement233
Formatting if elseStatements235
The if else if elseConstruction236
Logical Expressions238
The Logical OR Operator: ||238
The Logical AND Operator: &&239
The Logical NOT Operator: !244
Logical Operator Facts246
Alternative Representations247
The cctypeLibrary of Character Functions247
The ?: Operator250
The switchStatement251
Using Enumerators as Labels255
switchand if else256
The breakand continueStatements256
Program Notes258

Compound Statements, or Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .193 viiiC++ PRIMER PLUS, FIFTH EDITION

Program Notes262
Simple File Input/Output262
Text I/O and Text Files263
Writing to a Text File264
Reading from a Text File268
Summary273
Review Questions274
Programming Exercises276
CHAPTER 7:Functions: C++’s Programming Modules279
Function Review280
Defining a Function281
Prototyping and Calling a Function283
Function Arguments and Passing by Value286
Multiple Arguments288
Another Two-Argument Function290
Functions and Arrays293
How Pointers Enable Array-Processing Functions294
The Implications of Using Arrays as Arguments295
More Array Function Examples297
Functions Using Array Ranges303
Pointers and const305
Functions and Two-Dimensional Arrays308
Functions and C-Style Strings309
Functions with C-Style String Arguments310
Functions That Return C-Style Strings312
Functions and Structures313
Passing and Returning Structures314
Another Example of Using Functions with Structures316
Passing Structure Addresses320
Functions and stringClass Objects322
Recursion324
Recursion with a Single Recursive Call324
Recursion with Multiple Recursive Calls326
Pointers to Functions327
Function Pointer Basics328
A Function Pointer Example330
Summary332
Review Questions3
Programming Exercises334

Number-Reading Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .259 ixCONTENTS

C++ Inline Functions337
Reference Variables340
Creating a Reference Variable341
References as Function Parameters344
Reference Properties and Oddities347
Using References with a Structure351
Using References with a Class Object355
Another Object Lesson: Objects, Inheritance, and References358
When to Use Reference Arguments361
Default Arguments362
Program Notes364
Function Overloading365
An Overloading Example367
When to Use Function Overloading370
Function Templates370
Overloaded Templates374
Explicit Specializations376
Instantiations and Specializations380
Which Function Version Does the Compiler Pick?382
Summary388
Review Questions389
Programming Exercises390
CHAPTER 9:Memory Models and Namespaces393
Separate Compilation393
Storage Duration, Scope, and Linkage399
Scope and Linkage399
Automatic Storage Duration400
Static Duration Variables406
Specifiers and Qualifiers415
Functions and Linkage418
Language Linking419
Storage Schemes and Dynamic Allocation419
The Placement newOperator420
Program Notes423
Namespaces424
Traditional C++ Namespaces424
New Namespace Features426
A Namespace Example433
Namespaces and the Future437
Summary437

CHAPTER 8:Adventures in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .337 xC++ PRIMER PLUS, FIFTH EDITION

Programming Exercises441
CHAPTER 10:Objects and Classes445
Procedural and Object-Oriented Programming446
Abstraction and Classes447
What Is a Type?447
Classes in C++448
Implementing Class Member Functions453
Using Classes458
Reviewing Our Story to Date462
Class Constructors and Destructors463
Declaring and Defining Constructors464
Using Constructors465
Default Constructors466
Destructors467
Improving the StockClass468
Constructors and Destructors in Review475
Knowing Your Objects: The thisPointer477
An Array of Objects483
The Interface and Implementation Revisited486
Class Scope487
Class Scope Constants488
Abstract Data Types489
Summary495
Review Questions496
Programming Exercises496
CHAPTER 1:Working with Classes501
Operator Overloading502
Time on Our Hands: Developing an Operator Overloading Example503
Adding an Addition Operator506
Overloading Restrictions510
More Overloaded Operators512
Introducing Friends515
Creating Friends516
A Common Kind of Friend: Overloading the << Operator518
Overloaded Operators: Member Versus Nonmember Functions524
More Overloading: A Vector Class525
Using a State Member533
Overloading Arithmetic Operators for the VectorClass535
An Implementation Comment537
Taking the VectorClass on a Random Walk538

Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .438 xiCONTENTS

Program Notes547
Conversion Functions547
Conversions and Friends553
Summary556
Review Questions558
Programming Exercises558
CHAPTER 12:Classes and Dynamic Memory Allocation561
Dynamic Memory and Classes562
A Review Example and Static Class Members562
Implicit Member Functions571
The New, Improved StringClass579
Things to Remember When Using newin Constructors590
Observations About Returning Objects593
Using Pointers to Objects596
Reviewing Techniques606
A Queue Simulation607
A Queue Class608
The CustomerClass618
The Simulation621
Summary626
Review Questions627
Programming Exercises629
CHAPTER 13:Class Inheritance633
Beginning with a Simple Base Class634
Deriving a Class636
Constructors: Access Considerations638
Using a Derived Class641
Special Relationships Between Derived and Base Classes643
Inheritance: An Is-aRelationship645
Polymorphic Public Inheritance647
Developing the Brassand BrassPlusClasses648
Static and Dynamic Binding660
Pointer and Reference Type Compatibility660
Virtual Member Functions and Dynamic Binding662
Things to Know About Virtual Methods664
Access Control: protected668
Abstract Base Classes670
Applying the ABC Concept672
ABC Philosophy677

Automatic Conversions and Type Casts for Classes . . . . . . . . . . . . . . . . . . . .541 xiiC++ PRIMER PLUS, FIFTH EDITION

Case 1: Derived Class Doesn’t Use new677
Case 2: Derived Class Does Use new679
Friends681
Class Design Review685
Member Functions That the Compiler Generates for You686
Other Class Method Considerations687
Public Inheritance Considerations691
Class Function Summary695
Summary696
Review Questions697
Programming Exercises698
CHAPTER 14:Reusing Code in C++701
Classes with Object Members701
The valarrayClass: A Quick Look702
The StudentClass Design703
The StudentClass Example705
Private Inheritance712
The StudentClass Example (New Version)713
Multiple Inheritance723
How Many Workers?728
Which Method?732
MI Synopsis743
Class Templates744
Defining a Class Template744
Using a Template Class748
A Closer Look at the Template Class750
An Array Template Example and Non-Type Arguments756
Template Versatility758
Template Specializations762
Member Templates765
Templates as Parameters768
Template Classes and Friends770
Summary7
Review Questions779
Programming Exercises781

Inheritance and Dynamic Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . .677 An Inheritance Example with Dynamic Memory Allocation and xiiiCONTENTS

Friends787
Friend Classes788
Friend Member Functions793
Other Friendly Relationships796
Nested Classes798
Nested Classes and Access800
Nesting in a Template801
Exceptions805
Calling abort()805
Returning an Error Code807
The Exception Mechanism808
Using Objects as Exceptions812
Unwinding the Stack816
More Exception Features822
The exceptionClass824
Exceptions, Classes, and Inheritance829
When Exceptions Go Astray834
Exception Cautions837
RTTI839
What Is RTTI For?840
How Does RTTI Work?840
Type Cast Operators848
Summary852
Review Questions853
Programming Exercises854
CHAPTER 16:The stringClass and the Standard Template Library857
The stringClass857
Constructing a String858
stringClass Input862
Working with Strings864
What Else Does the stringClass Offer?870
The auto_ptrClass873
Using auto_ptr874
auto_ptrConsiderations876
The STL877
The vectorTemplate Class878
Things to Do to Vectors880
More Things to Do to Vectors885

CHAPTER 15:Friends, Exceptions, and More . . . . . . . . . . . . . . . . . . . . . . . . . .787 xivC++ PRIMER PLUS, FIFTH EDITION

Why Iterators?890
Kinds of Iterators894
Iterator Hierarchy897
Concepts, Refinements, and Models898
Kinds of Containers905
Associative Containers915
Function Objects (aka Functors)922
Functor Concepts923
Predefined Functors926
Adaptable Functors and Function Adapters928
Algorithms930
Algorithm Groups931
General Properties of Algorithms932
The STL and the stringClass933
Functions Versus Container Methods934
Using the STL936
Other Libraries940
vectorand valarray940
Summary946
Review Questions948
Programming Exercises949
CHAPTER 17:Input, Output, and Files951
An Overview of C++ Input and Output952
Streams and Buffers952
Streams, Buffers, and the iostreamFile955
Redirection957
Output with cout958
The Overloaded << Operator958
The Other ostreamMethods961
Flushing the Output Buffer964
Formatting with cout965
Input with cin983
How cin >>Views Input985
Stream States987
Other istreamClass Methods991
Other istreamMethods9
File Input and Output1003
Simple File I/O1004
Stream Checking and is_open()1007
Opening Multiple Files1008

Generic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .890 xvCONTENTS

File Modes1011
Random Access1021
Incore Formatting1030
What Now?1032
Summary1033
Review Questions1034
Programming Exercises1036
APPENDIX A:Number Bases1041
Decimal Numbers (Base 10)1041
Octal Integers (Base 8)1041
Hexadecimal Numbers (Base 16)1042
Binary Numbers (Base 2)1043
Binary and Hex1043
APPENDIX B:C++ Reserved Words1047
C++ Keywords1047
Alternative Tokens1048
C++ Library Reserved Names1048
APPENDIX C:The ASCII Character Set1051
APPENDIX D:Operator Precedence1057
APPENDIX E:Other Operators1063
Bitwise Operators1063
The Shift Operators1063
The Logical Bitwise Operators1065
Alternative Representations of Bitwise Operators1067
A Few Common Bitwise Operator Techniques1068
Member Dereferencing Operators1070
APPENDIX F:The stringTemplate Class1075
Thirteen Types and a Constant1076
Data Information, Constructors, and Odds and Ends1077
Default Constructors1079
Constructors That Use Arrays1079
Constructors That Use Part of an Array1080
Copy Constructors1080
Constructors That Use nCopies of a Character1081
Constructors That Use a Range1082
Memory Miscellany1082
String Access1083
Basic Assignment1084

Command-Line Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1008 xviC++ PRIMER PLUS, FIFTH EDITION

The find()Family1084
The rfind()Family1085
The find_first_of()Family1086
The find_last_of()Family1086
The find_first_not_of()Family1087
The find_last_not_of()Family1087
Comparison Methods and Functions1088
String Modifiers1089
Methods for Appending and Adding1089
More Assignment Methods1090
Insertion Methods1091
Erase Methods1091
Replacement Methods1092
Other Modifying Methods: copy()and swap()1093
Output and Input1093
APPENDIX G:The STL Methods and Functions1095
Members Common to All Containers1095
Additional Members for Vectors, Lists, and Deques1098
Additional Members for Sets and Maps1101
STL Functions1102
Nonmodifying Sequence Operations1103
Mutating Sequence Operations1107
Sorting and Related Operations1115
Numeric Operations1126
APPENDIX H:Selected Readings and Internet Resources1129
Selected Readings1129
Internet Resources1131
APPENDIX I:Converting to ANSI/ISO Standard C++13
Use Alternatives for Some Preprocessor Directives13
Use constInstead of #defineto Define Constants13
Use inlineInstead of #defineto Define Short Functions1135
Use Function Prototypes1136
Use Type Casts1136
Become Familiar with C++ Features1137
Use the New Header Organization1137
Use Namespaces1137
Use the autoptrTemplate1138
Use the stringClass1139
Use the STL1139

String Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1084 xviiCONTENTS

Answers to Review Questions for Chapter 21141
Answers to Review Questions for Chapter 31142
Answers to Review Questions for Chapter 41143
Answers to Review Questions for Chapter 514
Answers to Review Questions for Chapter 61145
Answers to Review Questions for Chapter 71147
Answers to Review Questions for Chapter 81148
Answers to Review Questions for Chapter 91150
Answers to Review Questions for Chapter 101151
Answers to Review Questions for Chapter 1154
Answers to Review Questions for Chapter 1215
Answers to Review Questions for Chapter 131157
Answers to Review Questions for Chapter 141159
Answers to Review Questions for Chapter 151160
Answers to Review Questions for Chapter 161161
Answers to Review Questions for Chapter 171162

APPENDIX J:Answers to the Review Questions . . . . . . . . . . . . . . . . . . . . . . . .1141 INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1165

Stephen Pratateaches astronomy, physics, and computer science at the College of Marin in Kentfield, California. He received his B.S. from the California Institute of Technology and his Ph.D. from the University of California, Berkeley. Stephen has authored or coauthored more than a dozen books for The Waite Group.He wrote The Waite Group’s New C Primer Plus, which received the Computer Press Association’s 1990 Best How-to Computer Book Award, and The Waite Group’s C++ Primer Plus, nominated for the Computer Press Association’s Best How-to Computer Book Award in 1991.

To my colleagues and students at the College of Marin, with whom it is a pleasure to work.

—Stephen Prata

Acknowledgments for the Fifth Edition

I’d like to thank Loretta Yates and Songlin Qiu of Sams Publishing for guiding and managing this project. Thanks to my colleague Fred Schmitt for several useful suggestions. Once again, I’d like to thank Ron Liechty of Metrowerks for his helpfulness.

Acknowledgments for the Fourth Edition

Several editors from Pearson and from Sams helped originate and maintain this project; thanks to Linda Sharp, Karen Wachs, and Laurie McGuire. Thanks, too, to Michael Maddox, Bill Craun, Chris Maunder, and Phillipe Bruno for providing technical review and editing. And thanks again to Michael Maddox and Bill Craun for supplying the material for the Real World Notes. Finally, I’d like to thank Ron Liechty of Metrowerks and Greg Comeau of Comeau Computing for their aid with C++ compilers.

Acknowledgments for the Third Edition

I’d like to thank the editors from Macmillan and The Waite Group for the roles they played in putting this book together: Tracy Dunkelberger, Susan Walton, and Andrea Rosenberg. Thanks, too, to Russ Jacobs for his content and technical editing. From Metrowerks, I’d like to thank Dave Mark, Alex Harper, and especially Ron Liechty, for their help and cooperation.

Acknowledgments for the Second Edition

I’d like to thank Mitchell Waite and Scott Calamar for supporting a second edition and Joel Fugazzotto and Joanne Miller for guiding the project to completion. Thanks to Michael Marcotty of Metrowerks for dealing with my questions about their beta version CodeWarrior compiler. I’d also like to thank the following instructors for taking the time to give us feedback on the first edition: Jeff Buckwalter, Earl Brynner, Mike Holland, Andy Yao, Larry Sanders,

Shahin Momtazi, and Don Stephens. Finally, I wish to thank Heidi Brumbaugh for her helpful content editing of new and revised material.

Acknowledgments for the First Edition

Many people have contributed to this book. In particular, I wish to thank Mitch Waite for his work in developing, shaping, and reshaping this book, and for reviewing the manuscript. I appreciate Harry Henderson’s work in reviewing the last few chapters and in testing programs with the Zortech C++ compiler. Thanks to David Gerrold for reviewing the entire manuscript and for championing the needs of less-experienced readers. Also thanks to Hank Shiffman for testing programs using Sun C++ and to Kent Williams for testing programs with AT&T cfront and with G++. Thanks to Nan Borreson of Borland International for her responsive and cheerful assistance with Turbo C++ and Borland C++. Thank you, Ruth Myers and Christine Bush, for handling the relentless paper flow involved with this kind of project. Finally, thanks to Scott Calamar for keeping everything on track.

As the reader of this book, youare our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do 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 an associate publisher for Sams Publishing, I welcome your comments. You can 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 do to make our books better.

Please note that I cannot help you with technical problems related to the topic of this book. We do have a User Services group, however, where I will forward specific technical questions related to the book.

When you write, please be sure to include this book’s title and author as well as your name, email address, and phone number. I will carefully review your comments and share them with the author and editors who worked on the book.

Email: feedback@samspublishing.com

Mail: Michael Stephens

Associate Publisher Sams Publishing 800 East 96th Street Indianapolis, IN 46240 USA

For more information about this book or another Sams Publishing title, visit our web site at w.samspublishing.com. Type the ISBN (0672326973) or the title of a book in the Search field to find the page you’re looking for.

Preface to the Fifth Edition

Learning C++ is an adventure of discovery, particularly because the language accommodates several programming paradigms, including object-oriented programming, generic programming, and the traditional procedural programming. C++ was a moving target as the language added new features, but now, with the ISO/ANSI C++ Standard, Second Edition (2003), in place, the language has stabilized. Contemporary compilers support most or all of the features mandated by the standard, and programmers have had time to get used to applying these features. The fifth edition of this book, C++ Primer Plus,reflects the ISO/ANSI standard and describes this matured version of C++.

C++ Primer Plus discusses the basic C language and presents C++ features, making this book self-contained. It presents C++ fundamentals and illustrates them with short, to-the-point programs that are easy to copy and experiment with. You’l learn about input/output (I/O), how to make programs perform repetitive tasks and make choices, the many ways to handle data, and how to use functions. You’l learn about the many features C++ has added to C, including the following:

•Classes and objects

• Inheritance

•Polymorphism, virtual functions, and runtime type identification (RTTI)

• Function overloading

• Reference variables

•Generic, or type-independent, programming, as provided by templates and the Standard Template Library (STL)

•The exception mechanism for handling error conditions

•Namespaces for managing names of functions, classes, and variables

The Primer Approach

C++ Primer Plusbrings several virtues to the task of presenting all this material. It builds on the primer tradition begun by C Primer Plusnearly two decades ago and embraces its successful philosophy:

•A primer should be an easy-to-use, friendly guide.

•A primer doesn’t assume that you are already familiar with all relevant programming concepts.

•A primer emphasizes hands-on learning with brief, easily typed examples that develop your understanding, a concept or two at a time.

•A primer clarifies concepts with illustrations.

•A primer provides questions and exercises to let you test your understanding, making the book suitable for self-learning or for the classroom.

Following these principles, the book helps you understand this rich language and how to use it. For example:

•It provides conceptual guidance about when to use particular features, such as using public inheritance to model what are known as is-arelationships.

•It illustrates common C++ programming idioms and techniques.

•It provides a variety of sidebars, including tips, cautions, things to remember, compatibility notes, and real-world notes.

The author and editors of this book do our best to keep the presentation to-the-point, simple, and fun. Our goal is that by the end of the book, you’l be able to write solid, effective programs and enjoy yourself doing so.

Sample Code Used in This Book

This book provides an abundance of sample code, most of it in the form of complete programs. Like the previous editions, this book practices generic C++ so that it is not tied to any particular kind of computer, operating system, or compiler. Thus, the examples were tested on a Windows XP system, a Macintosh OS X system, and a Linux system. Only a few programs were affected by compiler non-conformance issues. Compiler compliance with the C++ standard has improved since the previous edition of this book first appeared.

The sample code for the complete programs described in this book is available on the Sams website, at w.samspublishing.com. Enter this book’s ISBN (without the hyphens) in the Search box and click Search. When the book’s title is displayed, click the title to go to a page where you can download the code. You also can find solutions to selected programming exercises at this site.

How This Book Is Organized This book is divided into 17 chapters and 10 appendixes, summarized here.

2C++ PRIMER PLUS, FIFTH EDITION

Chapter 1: Getting Started

Chapter 1 relates how Bjarne Stroustrup created the C++ programming language by adding object-oriented programming support to the C language. You’l learn the distinctions between procedural languages, such as C, and object-oriented languages, such as C++. You’l read about the joint ANSI/ISO work to develop a C++ standard. This chapter discusses the mechanics of creating a C++ program, outlining the approach for several current C++ compilers. Finally, it describes the conventions used in this book.

Chapter 2: Setting Out to C++

Chapter 2 guides you through the process of creating simple C++ programs. You’l learn about the role of the main()function and about some of the kinds of statements that C++ programs use. You’l use the predefined coutand cinobjects for program output and input, and you’l learn about creating and using variables. Finaly, you’l be introduced to functions, C++’s programming modules.

Chapter 3: Dealing with Data

C++ provides built-in types for storing two kinds of data: integers (numbers with no fractional parts) and floating-point numbers (numbers with fractional parts). To meet the diverse requirements of programmers, C++ offers several types in each category. Chapter 3 discusses those types, including creating variables and writing constants of various types. You’l also learn how C++ handles implicit and explicit conversions from one type to another.

Chapter 4: Compound Types

C++ lets you construct more elaborate types from the basic built-in types. The most advanced form is the class, discussed in Chapters 9 through 13. Chapter 4 discusses other forms, including arrays, which hold several values of a single type; structures, which hold several values of unlike types; and pointers, which identify locations in memory. You’l also learn how to create and store text strings and to handle text I/O by using C-style character arrays and the C++ stringclass. Finaly, you’l learn some of the ways C++ handles memory alocation, including using the newand deleteoperators for managing memory explicitly.

(Parte 1 de 5)

Comentários