Tải bản đầy đủ (.pdf) (886 trang)

Jesse liberty, siddhartha rao, bradley jones teach youserf c++ in one hour a day

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (12.13 MB, 886 trang )

in One Hour aDay
C++
SamsTeach Yourself
Jesse Liberty
Siddhartha Rao
Bradley Jones
800 East 96th Street, Indianapolis, Indiana 46240
Sams Teach Yourself C++ in One Hour a Day
Copyright © 2009 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 permis-
sion from the publisher. No patent liability is assumed with respect to the use of the information con-
tained 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.
ISBN-13: 978-0-672-32941-8
ISBN-10: 0-672-32941-7
Library of Congress Cataloging-in-Publication Data
Liberty, Jesse.
C++ in one hour a day / Jesse Liberty, Siddhartha Rao, Bradley Jones. — 6th ed.
p. cm.
Includes bibliographical references and index.
ISBN 978-0-672-32941-8 (pbk.)
1. C++ (Computer program language) I. Rao, Siddhartha. II. Jones, Bradley. III. Title.
QA76.73.C153L528 2008
005.13’3—dc22
2008024283
Printed in the United States of America
First Printing July 2008
Trademarks


All terms mentioned in this book that are known to be trademarks or service marks have been appropri-
ately 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. The authors and the publisher shall
have neither liability nor responsibility to any person or entity with respect to any loss or damages aris-
ing from the information contained in this book or from the use of the CD or programs accompanying it.
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

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

Acquisitions Editor
Mark Taber
Development Editor
Songlin Qiu
Managing Editor
Patrick Kanouse
Project Editor
Seth Kerney
Copy Editor
Mike Henry
Indexer
WordWise Publishing
Services, LLC

Proofreader
Kathy Ruiz
Technical Editors
Jon Upchurch
Dr. Mark S. Merry
Publishing
Coordinator
Vanessa Evans
Book Designer
Gary Adair
Contents at a Glance
Introduction 1
PART I: The Basics
1 Getting Started 7
2 The Anatomy of a C++ Program 27
3 Using Variables, Declaring Constants 43
4 Managing Arrays and Strings 71
5 Working with Expressions, Statements, and Operators 93
6 Organizing Code with Functions 127
7 Controlling Program Flow 167
8 Pointers Explained 203
9 Exploiting References 231
PART II: Fundamentals of Object-Oriented Programming and C++
10 Classes and Objects 265
11 Implementing Inheritance 301
12 Polymorphism 343
13 Operator Types and Operator Overloading 385
14 Casting Operators 415
15 An Introduction to Macros and Templates 427
PART III: Learning the Standard Template Library (STL)

16 An Introduction to the Standard Template Library 447
17 The STL string Class 457
18 STL Dynamic Array Classes 473
19 STL list 491
20 STL set and multiset 513
21 STL map and multimap 533
PART IV: More STL
22 Understanding Function Objects 553
23 STL Algorithms 569
24 Adaptive Containers: stack and queue 601
25 Working with Bit Flags Using STL 617
PART V: Advanced C++ Concepts
26 Understanding Smart Pointers 629
27 Working with Streams 643
28 Exception Handling 689
29 Tapping Further into the Preprocessor 727
Appendixes
A Working with Numbers: Binary and Hexadecimal 763
B C++ Keywords 773
C Operator Precedence 775
D Answers 777
Index 829
Table of Contents
Introduction 1
Who Should Read This Book 1
Organization of This Book
1
Conventions Used in This Book
2
Sample Code for This Book

3
PART I: The Basics
LESSON 1: Getting Started 7
A Brief History of C++ 8
Interpreters and Compilers
9
Changing Requirements, Changing Platforms
10
Procedural, Structured, and Object-Oriented Programming
11
Object-Oriented Programming
12
C++ and Object-Oriented Programming
12
How C++ Evolved
14
Should I Learn C First?
14
Microsoft’s Managed Extensions to C++
14
The ANSI Standard
14
Preparing to Program
15
Your Development Environment
16
The Process of Creating the Program
17
Creating an Object File with the Compiler
17

Creating an Executable File with the Linker
18
The Development Cycle
18
HELLO.cpp—Your First C++ Program 19
Getting Started with Your Compiler
22
Building the Hello World Project
22
Compile Errors
23
Summary
24
Q&A
24
Workshop
25
LESSON 2: The Anatomy of a C++ Program 27
A Simple Program 28
A Brief Look at
cout 30
Using the Standard Namespace
32
Commenting Your Programs
35
Types of Comments
35
Using Comments
36
A Final Word of Caution About Comments

37
Functions
37
Using Functions
38
Methods Versus Functions
41
Summary
41
Q&A
41
Workshop
42
LESSON 3: Using Variables, Declaring Constants 43
What Is a Variable? 44
Storing Data in Memory
44
Setting Aside Memory
45
Size of Integers
45
signed and unsigned 46
Fundamental Variable Types
47
Defining a Variable
48
Case Sensitivity
49
Naming Conventions
49

Keywords
50
Determining Memory Consumed by a Variable Type
51
Creating More Than One Variable at a Time
53
Assigning Values to Your Variables
53
Creating Aliases with
typedef 55
When to Use
short and When to Use long 56
Wrapping Around an
unsigned Integer 57
Wrapping Around a
signed Integer 58
Working with Characters
59
Characters and Numbers
60
Special Printing Characters
61
vi
Sams Teach Yourself C++ in One Hour a Day

Understanding Operator Precedence 103
Nesting Parentheses
104
The Nature of Truth
105

Evaluating with the Relational Operators
105
The
if Statement 107
Indentation Styles
110
The
else Statement 111
Advanced
if Statements 113
Using Braces in Nested
if Statements 115
Using the Logical Operators
118
The Logical
AND Operator 118
The Logical
OR Operator 119
The Logical
NOT Operator 119
Short Circuit Evaluation
119
Relational Precedence
120
More About Truth and Falsehood
120
The Conditional (Ternary) Operator
121
Summary
123

Q&A
123
Workshop
124
LESSON 6: Organizing Code with Functions 127
What Is a Function? 128
Return Values, Parameters, and Arguments
129
Declaring and Defining Functions
129
Function Prototypes
130
Defining the Function
131
Execution of Functions
133
Determining Variable Scope
134
Local Variables
134
Local Variables Within Blocks
136
Parameters Are Local Variables
137
Global Variables
139
Global Variables: A Word of Caution
140
Considerations for Creating Function Statements
141

viii
Sams Teach Yourself C++ in One Hour a Day
More About Function Arguments 141
More About Return Values
142
Default Parameters
145
Overloading Functions
147
Special Topics About Functions
151
Inline Functions
151
Recursion
153
How Functions Work—A Peek Under the Hood
158
Levels of Abstraction
159
Summary
163
Q&A
163
Workshop
164
LESSON 7: Controlling Program Flow 167
Programming Loops 168
The Roots of Looping:
goto 168
Why

goto Is Shunned 169
Using
while Loops 169
Exploring More Complicated
while Statements 171
Introducing
continue and break 173
Examining
while(true) Loops 176
Implementing
do while Loops 177
Using
do while 178
Looping with the
for Statement 180
Advanced
for Loops 183
Empty
for Loops 186
Nesting Loops
187
Scoping in
for Loops 189
Summing Up Loops
189
Controlling Flow with
switch Statements 192
Using a
switch Statement with a Menu 195
Summary

199
Q&A
199
Workshop
200
Contents
ix
LESSON 8: Pointers Explained 203
What Is a Pointer? 204
A Bit About Memory
204
Getting a Variable’s Memory Address
204
Storing a Variable’s Address in a Pointer
206
Pointer Names
206
Getting the Value from a Variable
207
Dereferencing with the Indirection Operator
208
Pointers, Addresses, and Variables
209
Manipulating Data by Using Pointers
210
Examining the Address
212
Pointers and Array Names
213
A Pointer to an Array Versus an Array of Pointers

215
Why Would You Use Pointers?
216
The Stack and the Free Store (Heap)
216
Allocating Space with the
new Keyword 218
Putting Memory Back: The
delete Keyword 219
Another Look at Memory Leaks
221
Creating Objects on the Free Store
222
Deleting Objects from the Free Store
222
Stray, Wild, or Dangling Pointers
224
Using
const Pointers 227
Summary
228
Q&A
228
Workshop
229
LESSON 9: Exploiting References 231
What Is a Reference? 232
Using the Address-Of Operator (
&) on References 233
Attempting to Reassign References (Not!)

235
Null Pointers and Null References
237
Passing Function Arguments by Reference
237
Making
swap() Work with Pointers 239
Implementing
swap() with References 240
Returning Multiple Values
242
Returning Values by Reference
244
x
Sams Teach Yourself C++ in One Hour a Day
Passing by Reference for Efficiency 246
Passing a
const Pointer 249
References as an Alternative
252
Knowing When to Use References Versus Pointers
254
Mixing References and Pointers
255
Returning Out-of-Scope Object References
256
The Problem with Returning a Reference to an Object on the Heap/Free Store
258
Summary
259

Q&A
260
Workshop
260
PART II: Fundamentals of Object-Oriented Programming and C++
LESSON 10: Classes and Objects 265
Is C++ Object-Oriented? 266
Creating New Types
267
Introducing Classes and Members
268
Declaring a Class
269
A Word on Naming Conventions
269
Defining an Object
270
Classes Versus Objects
270
Accessing Class Members
271
Assigning to Objects, Not to Classes
271
If You Don’t Declare It, Your Class Won’t Have It
272
Private Versus Public Access
272
Making Member Data Private
275
Implementing Class Methods

278
Adding Constructors and Destructors
281
Getting a Default Constructor and Destructor
282
Using the Default Constructor
282
Including
const Member Functions 286
Where to Put Class Declarations and Method Definitions
287
Inline Implementation
288
Classes with Other Classes as Member Data
291
Exploring Structures
295
Summary
296
Q&A
297
Workshop
298
Contents
xi
LESSON 11: Implementing Inheritance 301
What Is Inheritance? 302
Inheritance and Derivation
302
The Animal Kingdom

303
The Syntax of Derivation
304
Private Versus Protected
306
Inheritance with Constructors and Destructors
309
Passing Arguments to Base Constructors
311
Overriding Base Class Functions
316
Hiding the Base Class Method
318
Calling the Base Method
320
Virtual Methods
322
How Virtual Functions Work
326
Trying to Access Methods from a Base Class
328
Slicing
328
Creating Virtual Destructors
330
Virtual Copy Constructors
331
The Cost of Virtual Methods
334
Private Inheritance

335
Using Private Inheritance
335
Private Inheritance Versus Aggregation (Composition)
337
Summary
338
Q&A
339
Workshop
340
LESSON 12: Polymorphism 343
Problems with Single Inheritance 344
Percolating Upward
346
Casting Down
347
Adding to Two Lists
350
Multiple Inheritance
351
The Parts of a Multiply Inherited Object
354
Constructors in Multiply Inherited Objects
355
Ambiguity Resolution
358
Inheriting from Shared Base Class
359
Virtual Inheritance

363
xii
Sams Teach Yourself C++ in One Hour a Day
Problems with Multiple Inheritance 367
Mixins and Capabilities Classes
368
Abstract Data Types
368
Pure Virtual Functions
372
Implementing Pure Virtual Functions
374
Complex Hierarchies of Abstraction
377
Which Classes Are Abstract?
381
Summary
382
Q&A
382
Workshop
383
LESSON 13: Operator Types and Operator Overloading 385
What Are Operators in C++? 386
Unary Operators
387
Types of Unary Operators
387
Programming a Unary Increment/Decrement Operator
387

Programming Dereference Operator
* and Member Selection Operator -> 391
Programming Conversion Operators
394
Binary Operators
396
Types of Binary Operators
396
Programming Binary Addition (a+b) and Subtraction (a–b) Operators
397
Programming Addition-Assignment and Subtraction-Assignment Operators
399
Overloading Comparison Operators
401
Overloading
<, >, <=, and >= Operators 405
Subscript Operators
409
Function
operator() 411
Operators That Cannot Be Redefined
412
Summary
413
Q&A
413
Workshop
414
LESSON 14: Casting Operators 415
What Is Casting? 416

The Need for Casting
416
Why C-Style Casts Are Not Popular with Some C++ Programmers
417
Contents
xiii

PART III: Learning the Standard Template Library (STL)
LESSON 16: An Introduction to the Standard Template Library 447
STL Containers 448
Sequential Containers
448
Associative Containers
448
Choosing the Right Container
449
STL Iterators
451
STL Algorithms
452
The Interaction Between Containers and Algorithms Using Iterators
453
Summary
455
Q&A
455
Workshop
456
LESSON 17: The STL string Class 457
The Need for String Manipulation Classes 458

Working with the STL
string Class 459
Instantiating the STL
string and Making Copies 459
Accessing a
string and Its Contents 461
String Concatenation
463
Finding a Character or Substring in a
string 464
Truncating an STL
string 467
String Reversal
468
String Case Conversion
469
Template-Based Implementation of an STL
string 471
Summary
471
Q&A
471
Workshop
472
LESSON 18: STL Dynamic Array Classes 473
The Characteristics of std::vector 474
Typical Vector Operations
474
Instantiating a
vector 474

Inserting Elements in a
vector 476
Accessing Elements in a
vector 480
Removing Elements from a
vector 482
Understanding
size() and capacity() 484
Contents
xv
The STL deque Class 486
Summary
488
Q&A
488
Workshop
489
LESSON 19: STL list 491
The Characteristics of a std::list 492
Basic
list Operations 492
Instantiating a
std::list Object 492
Inserting Elements at the Front of the
list 493
Inserting Elements at the Back of the
list 494
Inserting at the Middle of the
list 495
Erasing Elements in a

list 497
Reversing and Sorting Elements in a
list 500
Reversing Elements
500
Sorting Elements
502
Summary
511
Q&A
511
Workshop
512
LESSON 20: STL set and multiset 513
An Introduction 514
Basic STL
set and multiset Operations 514
Instantiating a
std::set Object 514
Inserting Elements in an STL
set or multiset 515
Finding Elements in an STL
set or multiset 517
Erasing Elements in an STL
set or multiset 519
Pros and Cons of Using STL
set and multiset 529
Summary
529
Q&A

530
Workshop
530
LESSON 21: STL map and multimap 533
A Brief Introduction 534
Basic STL
map and multimap Operations 534
Instantiating a
std::map Object 534
Inserting Elements in an STL
map or multimap 535
xvi
Sams Teach Yourself C++ in One Hour a Day
Finding Elements in an STL map or multimap 538
Erasing Elements from an STL
map or multimap 540
Supplying a Custom Sort Predicate
543
Summary
547
Q&A
547
Workshop
548
PART IV: More STL
LESSON 22: Understanding Function Objects 553
The Concept of Function Objects and Predicates 554
Typical Applications of Function Objects
554
Unary Functions

554
Unary Predicate
559
Binary Functions
561
Binary Predicate
563
Summary
566
Q&A
566
Workshop
567
LESSON 23: STL Algorithms 569
What Are STL Algorithms? 570
Classification of STL Algorithms
570
Nonmutating Algorithms
570
Mutating Algorithms
571
Usage of STL Algorithms
573
Counting and Finding Elements
573
Searching for an Element or a Range in a Collection
576
Initializing Elements in a Container to a Specific Value
578
Processing Elements in a Range Using

for_each 581
Performing Transformations on a Range Using
std::transform 583
Copy and Remove Operations
585
Replacing Values and Replacing Element Given a Condition
589
Sorting and Searching in a Sorted Collection, and Erasing Duplicates
591
Partitioning a Range
593
Inserting Elements in a Sorted Collection
595
Summary
598
Contents
xvii
Q&A 598
Workshop
599
LESSON 24: Adaptive Containers: stack and queue 601
The Behavioral Characteristics of Stacks and Queues 602
Stacks
602
Queues
602
Using the STL
stack Class 603
Instantiating the Stack
603

Stack Member Functions
604
Using the STL
queue Class 606
Instantiating the Queue
606
Member Functions of a
queue 607
Using the STL Priority Queue
610
Instantiating the
priority_queue Class 610
Member Functions of
priority_queue 611
Summary
615
Q&A
615
Workshop
615
LESSON 25: Working with Bit Flags Using STL 617
The bitset Class 618
Instantiating the
std::bitset 618
Using
std::bitset and Its Members 619
std:bitset Operators 619
std::bitset Member Methods 620
The
vector<bool> 623

Instantiating a
vector<bool> 623
Using the
vector<bool> 624
Summary
625
Q&A
625
Workshop
626
xviii
Sams Teach Yourself C++ in One Hour a Day
PART V: Advanced C++ Concepts
LESSON 26: Understanding Smart Pointers 629
What Are Smart Pointers? 630
What Is the Problem with Using Conventional (Raw) Pointers?
630
How Do Smart Pointers Help?
630
How Are Smart Pointers Implemented?
631
Types of Smart Pointers
632
Deep Copy
633
Copy on Write Mechanism
635
Reference Counted Smart Pointers
635
Reference-Linked Smart Pointers

636
Destructive Copy
636
Using the
std::auto_ptr 638
Popular Smart Pointer Libraries
640
Summary
640
Q&A
641
Workshop
641
LESSON 27: Working with Streams 643
Overview of Streams 644
Encapsulation of Data Flow
644
Understanding Buffering
645
Streams and Buffers
647
Standard I/O Objects
647
Redirection of the Standard Streams
648
Input Using
cin 649
Inputting Strings
651
String Problems

651
The
cin Return Value 654
Other Member Functions of
cin 654
Single Character Input
655
Getting Strings from Standard Input
657
Using
cin.ignore() 660
Peeking At and Returning Characters:
peek() and putback() 662
Contents
xix
Outputting with cout 663
Flushing the Output
663
Functions for Doing Output
664
Manipulators, Flags, and Formatting Instructions
666
Streams Versus the
printf() Function 671
File Input and Output
675
Using the
ofstream 675
Condition States
675

Opening Files for Input and Output
675
Changing the Default Behavior of
ofstream on Open 677
Binary Versus Text Files
680
Command-Line Processing
682
Summary
686
Q&A
687
Workshop
687
LESSON 28: Exception Handling 689
Bugs, Errors, Mistakes, and Code Rot 690
Exceptional Circumstances
691
The Idea Behind Exceptions
692
The Parts of Exception Handling
693
Causing Your Own Exceptions
696
Creating an Exception Class
698
Placing
try Blocks and catch Blocks 702
How Catching Exceptions Work
702

Using More Than One
catch Specification 703
Exception Hierarchies
706
Data in Exceptions and Naming Exception Objects
709
Exceptions and Templates
716
Exceptions Without Errors
719
Bugs and Debugging
721
Breakpoints
721
Watch Points
721
Examining Memory
722
Assembler
722
Summary
722
xx
Sams Teach Yourself C++ in One Hour a Day

Spelling and Capitalization of Names 753
Comments
754
Setting Up Access
754

Class Definitions
755
include Files 755
Using
assert() 755
Making Items Constant with
const 755
Next Steps in Your C++ Development
756
Where to Get Help and Advice
756
Related C++ Topics: Managed C++, C#, and Microsoft’s .NET
756
Summary
757
Q&A
758
Workshop
759
Appendixes
APPENDIX A: Working with Numbers: Binary and Hexadecimal 763
Using Other Bases 764
Converting to Different Bases
765
Hexadecimal
768
APPENDIX B: C++ Keywords 773
APPENDIX C: Operator Precedence 775
APPENDIX D: Answers 777
Index 829

Lead Author, Sixth Edition
Siddhartha Rao is a Microsoft Most Valuable Professional for Visual C++ and a moder-
ator at one of the Internet’s most vibrant online development communities, CodeGuru.
“Sid,” as he is popularly known, is an expert in the Windows programming domain, and
is experienced in the architecture and development of driver and application software
using C++ and other modern programming languages. Currently employed by a German
software giant, he specializes in software landscape management and best practices in
software development. With the international experience of having lived and worked in
three countries behind him, he believes that the travel bug has bit him, and firmly so! Sid
speaks many languages that have nothing to do with programming, and when he’s not
working, you will find him discovering new places on the planet, or shooting—using his
Canon, of course!
Contributing Authors
Jesse Liberty is the author of numerous books on software development, including best-
selling titles in C++ and .NET. He is the president of Liberty Associates, Inc., where he
provides custom programming, consulting, and training.
Bradley Jones, Microsoft MVP, Visual C++, can be referred to as a webmaster, man-
ager, coding grunt, executive editor, and various other things. His time and focus are on a
number of software development sites and channels, including Developer.com,
CodeGuru.com, DevX, VBForums, Gamelan, and other Jupitermedia-owned sites.
Acknowledgments
Siddhartha Rao: I am thankful to the editors—Songlin Qiu, Seth Kerney, and Mark
Taber—for their prompt and professional involvement that helped make this book a real-
ity. I am deeply endowed to my loved ones for their unconditional support, for tolerating
me spending my vacations on this project, and for helping me out with every little chore
that I could concentrate on this book, which I consider so important. I hope you enjoy
reading it!
Jesse Liberty: A new edition is another chance to acknowledge and to thank those folks
without whose support and help this book literally would have been impossible. First
among them remain Stacey, Robin, and Rachel Liberty.

Bradley Jones: I would also like to thank Mark Cashman, David Corbin, Songlin Qiu,
and a number of readers from the previous editions.

×