Siêu thị PDFTải ngay đi em, trời tối mất

Thư viện tri thức trực tuyến

Kho tài liệu với 50,000+ tài liệu học thuật

© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Sams Teach Yourself C++ in 21 Days
PREMIUM
Số trang
937
Kích thước
6.7 MB
Định dạng
PDF
Lượt xem
839

Sams Teach Yourself C++ in 21 Days

Nội dung xem thử

Mô tả chi tiết

C++

Jesse Liberty

Bradley Jones

FIFTH EDITION

Teach Yourself

in21Days

800 East 96th Street, Indianapolis, Indiana, 46240 USA

00 0672327112_fm.qxd 11/19/04 12:52 PM Page i

Sams Teach Yourself C++ in 21 Days,

Fifth Edition

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, photo￾copying, recording, or otherwise, without written permission from the pub￾lisher. 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-32711-2

Library of Congress Catalog Card Number: 2004096713

Printed in the United States of America

First Printing: December 2004

07 06 05 04 4 3 2 1

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. The authors and the publisher shall have neither liability nor

responsibility to any person or entity with respect to any loss or damages

arising from the information contained in this book.

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

[email protected]

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

International Sales

[email protected]

ASSOCIATE PUBLISHER

Michael Stephens

ACQUISITIONS EDITOR

Loretta Yates

DEVELOPMENT EDITOR

Songlin Qiu

MANAGING EDITOR

Charlotte Clapp

PROJECT EDITOR

Seth Kerney

COPY EDITOR

Karen Annett

INDEXER

Erika Millen

PROOFREADER

Paula Lowell

TECHNICAL EDITORS

Mark Cashman

David V. Corbin

PUBLISHING COORDINATOR

Cindy Teeters

MULTIMEDIA DEVELOPER

Dan Scherf

BOOK DESIGNER

Gary Adair

PAGE LAYOUT

Eric S. Miller

Julie Parks

00 0672327112_fm.qxd 11/19/04 12:52 PM Page ii

Contents at a Glance

Introduction 1

Week 1 At a Glance 3

Day 1 Getting Started 5

2 The Anatomy of a C++ Program 25

3 Working with Variables and Constants 41

4 Creating Expressions and Statements 67

5 Organizing into Functions 99

6 Understanding Object-Oriented Programming 137

7 More on Program Flow 175

Week 1 In Review 209

Week 2 At a Glance 219

Day 8 Understanding Pointers 221

9 Exploiting References 255

10 Working with Advanced Functions 289

11 Object-Oriented Analysis and Design 329

12 Implementing Inheritance 371

13 Managing Arrays and Strings 407

14 Polymorphism 449

Week 2 In Review 491

Week 3 At a Glance 503

Day 15 Special Classes and Functions 505

16 Advanced Inheritance 537

17 Working with Streams 593

18 Creating and Using Namespaces 637

19 Templates 659

20 Handling Errors and Exceptions 715

21 What’s Next 751

00 0672327112_fm.qxd 11/19/04 12:52 PM Page iii

Week 3 In Review 791

Appendixes

Appendix A Working with Numbers: Binary and Hexadecimal 807

B C++ Keywords 817

C Operator Precedence 819

D Answers 821

E A Look at Linked Lists 875

Index 887

00 0672327112_fm.qxd 11/19/04 12:52 PM Page iv

Contents

Introduction 1

Who Should Read This Book ..................................................................................1

Conventions Used in This Book ..............................................................................1

Sample Code for This Book ....................................................................................2

Week 1 At a Glance 3

A Note to C Programmers ......................................................................................3

Where You Are Going..............................................................................................3

1 Getting Started 5

A Brief History of C++ ..........................................................................................5

The Need for Solving Problems ........................................................................7

Procedural, Structured, and Object-Oriented Programming ..............................8

Object-Oriented Programming (OOP) ..............................................................9

C++ and Object-Oriented Programming............................................................9

How C++ Evolved ................................................................................................11

Should I Learn C First? ........................................................................................11

C++, Java, and C#..................................................................................................12

Microsoft’s Managed Extensions to C++..............................................................12

The ANSI Standard................................................................................................12

Preparing to Program ............................................................................................13

Your Development Environment ..........................................................................14

The Process of Creating the Program....................................................................15

Creating an Object File with the Compiler ......................................................15

Creating an Executable File with the Linker ..................................................15

The Development Cycle ........................................................................................16

HELLO.cpp—Your First C++ Program ..................................................................17

Getting Started with Your Compiler ......................................................................19

Building the Hello World Project ....................................................................19

Compile Errors ......................................................................................................20

Summary................................................................................................................21

Q&A ......................................................................................................................21

Workshop ..............................................................................................................22

Quiz ..................................................................................................................22

Exercises ..........................................................................................................23

2 The Anatomy of a C++ Program 25

A Simple Program ................................................................................................25

A Brief Look at cout ............................................................................................28

00 0672327112_fm.qxd 11/19/04 12:52 PM Page v

Using the Standard Namespace ............................................................................30

Commenting Your Programs..................................................................................32

Types of Comments..........................................................................................33

Using Comments ..............................................................................................33

A Final Word of Caution About Comments ....................................................34

Functions................................................................................................................35

Using Functions................................................................................................36

Methods Versus Functions................................................................................38

Summary................................................................................................................38

Q&A ......................................................................................................................38

Workshop ..............................................................................................................39

Quiz ..................................................................................................................39

Exercises ..........................................................................................................39

3 Working with Variables and Constants 41

What Is a Variable?................................................................................................41

Storing Data in Memory ..................................................................................42

Setting Aside Memory......................................................................................42

Size of Integers ................................................................................................43

signed and unsigned ........................................................................................45

Fundamental Variable Types ............................................................................45

Defining a Variable ................................................................................................47

Case Sensitivity ................................................................................................48

Naming Conventions ........................................................................................48

Keywords..........................................................................................................49

Creating More Than One Variable at a Time ........................................................50

Assigning Values to Your Variables ......................................................................50

Creating Aliases with typedef ..............................................................................52

When to Use short and When to Use long ..........................................................53

Wrapping Around an unsigned Integer............................................................54

Wrapping Around a signed Integer..................................................................55

Working with Characters ......................................................................................56

Characters and Numbers ..................................................................................57

Special Printing Characters ..............................................................................58

Constants................................................................................................................59

Literal Constants ..............................................................................................59

Symbolic Constants..........................................................................................59

Enumerated Constants ..........................................................................................61

Summary................................................................................................................63

Q&A ......................................................................................................................64

Workshop ..............................................................................................................65

Quiz ..................................................................................................................65

Exercises ..........................................................................................................66

vi Sams Teach Yourself C++ in 21 Days, Fifth Edition

00 0672327112_fm.qxd 11/19/04 12:52 PM Page vi

4 Creating Expressions and Statements 67

Starting with Statements........................................................................................68

Using Whitespace ............................................................................................68

Blocks and Compound Statements ..................................................................68

Expressions ............................................................................................................69

Working with Operators ........................................................................................70

Assignment Operators ......................................................................................71

Mathematical Operators ..................................................................................71

Combining the Assignment and Mathematical Operators ....................................73

Incrementing and Decrementing............................................................................74

Prefixing Versus Postfixing ..............................................................................75

Understanding Operator Precedence ....................................................................77

Nesting Parentheses ..............................................................................................78

The Nature of Truth ..............................................................................................79

Evaluating with the Relational Operators ........................................................79

The if Statement ..................................................................................................80

Indentation Styles ............................................................................................83

The else Statement ..........................................................................................84

Advanced if Statements ..................................................................................86

Using Braces in Nested if Statements ..................................................................88

Using the Logical Operators..................................................................................91

The Logical AND Operator ................................................................................91

The Logical OR Operator ..................................................................................91

The Logical NOT Operator ................................................................................92

Short Circuit Evaluation ........................................................................................92

Relational Precedence............................................................................................92

More About Truth and Falsehood..........................................................................93

The Conditional (Ternary) Operator......................................................................94

Summary................................................................................................................95

Q&A ......................................................................................................................96

Workshop ..............................................................................................................96

Quiz ..................................................................................................................97

Exercises ..........................................................................................................97

5 Organizing into Functions 99

What Is a Function? ............................................................................................100

Return Values, Parameters, and Arguments ........................................................100

Declaring and Defining Functions ......................................................................101

Function Prototypes........................................................................................102

Defining the Function ....................................................................................103

Execution of Functions ........................................................................................105

Determining Variable Scope ................................................................................105

Local Variables ..............................................................................................105

Local Variables Within Blocks ......................................................................107

Contents vii

00 0672327112_fm.qxd 11/19/04 12:52 PM Page vii

Parameters Are Local Variables ..........................................................................109

Global Variables..............................................................................................110

Global Variables: A Word of Caution ............................................................112

Considerations for Creating Function Statements ..............................................112

More About Function Arguments ........................................................................113

More About Return Values ..................................................................................114

Default Parameters ..............................................................................................116

Overloading Functions ........................................................................................118

Special Topics About Functions ..........................................................................121

Inline Functions..............................................................................................122

Recursion........................................................................................................124

How Functions Work—A Peek Under the Hood ................................................129

Levels of Abstraction......................................................................................129

Summary..............................................................................................................133

Q&A ....................................................................................................................134

Workshop ............................................................................................................134

Quiz ................................................................................................................135

Exercises ........................................................................................................135

6 Understanding Object-Oriented Programming 137

Is C++ Object-Oriented? ....................................................................................137

Creating New Types ............................................................................................139

Introducing Classes and Members ......................................................................140

Declaring a Class............................................................................................141

A Word on Naming Conventions ..................................................................141

Defining an Object ........................................................................................142

Classes Versus Objects ..................................................................................142

Accessing Class Members ..................................................................................142

Assigning to Objects, Not to Classes ............................................................143

If You Don’t Declare It, Your Class Won’t Have It........................................143

Private Versus Public Access ..............................................................................144

Making Member Data Private ........................................................................146

Implementing Class Methods ..............................................................................150

Adding Constructors and Destructors..................................................................153

Getting a Default Constructor and Destructor ..............................................153

Using the Default Constructor........................................................................154

Including const Member Functions ....................................................................157

Interface Versus Implementation ........................................................................158

Where to Put Class Declarations and Method Definitions..................................161

Inline Implementation..........................................................................................162

Classes with Other Classes as Member Data ......................................................165

Exploring Structures ............................................................................................169

viii Sams Teach Yourself C++ in 21 Days, Fifth Edition

00 0672327112_fm.qxd 11/19/04 12:52 PM Page viii

Summary..............................................................................................................170

Q&A ....................................................................................................................171

Workshop ............................................................................................................172

Quiz ................................................................................................................172

Exercises ........................................................................................................173

7 More on Program Flow 175

Looping................................................................................................................175

The Roots of Looping: goto ..........................................................................176

Why goto Is Shunned ....................................................................................176

Using while Loops ..............................................................................................177

Exploring More Complicated while Statements............................................179

Introducing continue and break ....................................................................180

Examining while (true) Loops....................................................................183

Implementing do...while Loops ........................................................................184

Using do...while ................................................................................................186

Looping with the for Statement..........................................................................187

Advanced for Loops ......................................................................................190

Empty for Loops............................................................................................192

Nesting Loops ................................................................................................193

Scoping in for Loops ....................................................................................195

Summing Up Loops ............................................................................................196

Controlling Flow with switch Statements ..........................................................198

Using a switch Statement with a Menu ........................................................201

Summary..............................................................................................................205

Q&A ....................................................................................................................205

Workshop ............................................................................................................206

Quiz ................................................................................................................206

Exercises ........................................................................................................206

Week 1 In Review 209

Week 2 At a Glance 219

Where You Are Going..........................................................................................219

8 Understanding Pointers 221

What Is a Pointer?................................................................................................222

A Bit About Memory......................................................................................222

Getting a Variable’s Memory Address............................................................222

Storing a Variable’s Address in a Pointer ......................................................224

Pointer Names ................................................................................................224

Getting the Value from a Variable ..................................................................225

Dereferencing with the Indirection Operator ................................................226

Pointers, Addresses, and Variables ................................................................227

Contents ix

00 0672327112_fm.qxd 11/19/04 12:52 PM Page ix

Manipulating Data by Using Pointers ............................................................228

Examining the Address ..................................................................................229

Why Would You Use Pointers?............................................................................232

The Stack and the Free Store (Heap) ..................................................................232

Allocating Space with the new Keyword........................................................234

Putting Memory Back: The delete Keyword................................................235

Another Look at Memory Leaks ........................................................................237

Creating Objects on the Free Store......................................................................238

Deleting Objects from the Free Store..................................................................238

Accessing Data Members ....................................................................................239

Creating Member Data on the Free Store............................................................241

The this Pointer ..................................................................................................243

Stray, Wild, or Dangling Pointers........................................................................245

Using const Pointers ..........................................................................................248

const Pointers and const Member Functions................................................249

Using a const this Pointers..........................................................................251

Summary..............................................................................................................251

Q&A ....................................................................................................................252

Workshop ............................................................................................................252

Quiz ................................................................................................................252

Exercises ........................................................................................................253

9 Exploiting References 255

What Is a Reference? ..........................................................................................255

Using the Address-Of Operator (&) on References..............................................257

Attempting to Reassign References (Not!) ....................................................259

Referencing Objects ............................................................................................260

Null Pointers and Null References ......................................................................262

Passing Function Arguments by Reference ........................................................262

Making swap() Work with Pointers ..............................................................264

Implementing swap() with References ..........................................................265

Understanding Function Headers and Prototypes ..............................................267

Returning Multiple Values ..................................................................................268

Returning Values by Reference ......................................................................270

Passing by Reference for Efficiency....................................................................271

Passing a const Pointer ..................................................................................274

References as an Alternative ..........................................................................277

Knowing When to Use References Versus Pointers ............................................279

Mixing References and Pointers..........................................................................280

Returning Out-of-Scope Object References ........................................................281

Returning a Reference to an Object on the Heap ..........................................283

Pointer, Pointer, Who Has the Pointer? ..............................................................285

x Sams Teach Yourself C++ in 21 Days, Fifth Edition

00 0672327112_fm.qxd 11/19/04 12:52 PM Page x

Summary..............................................................................................................286

Q&A ....................................................................................................................286

Workshop ............................................................................................................287

Quiz ................................................................................................................287

Exercises ........................................................................................................287

10 Working with Advanced Functions 289

Overloaded Member Functions ..........................................................................289

Using Default Values ..........................................................................................292

Choosing Between Default Values and Overloaded Functions ..........................294

The Default Constructor ......................................................................................294

Overloading Constructors ....................................................................................295

Initializing Objects ..............................................................................................297

The Copy Constructor..........................................................................................298

Operator Overloading ..........................................................................................302

Writing an Increment Function ......................................................................303

Overloading the Prefix Operator ....................................................................304

Returning Types in Overloaded Operator Functions......................................306

Returning Nameless Temporaries ..................................................................307

Using the this Pointer ..................................................................................309

Overloading the Postfix Operator ..................................................................311

Difference Between Prefix and Postfix ..........................................................311

Overloading Binary Mathematical Operators ................................................313

Issues in Operator Overloading......................................................................316

Limitations on Operator Overloading ............................................................316

What to Overload ..........................................................................................317

The Assignment Operator ..............................................................................317

Handling Data Type Conversion..........................................................................320

Conversion Operators ..........................................................................................323

Summary..............................................................................................................325

Q&A ....................................................................................................................325

Workshop ............................................................................................................326

Quiz ................................................................................................................326

Exercises ........................................................................................................327

11 Object-Oriented Analysis and Design 329

Building Models ..................................................................................................329

Software Design: The Modeling Language ........................................................330

Software Design: The Process ............................................................................331

Waterfall Versus Iterative Development ........................................................332

The Process of Iterative Development ..........................................................333

Step 1: The Conceptualization Phase: Starting with The Vision ........................335

Contents xi

00 0672327112_fm.qxd 11/19/04 12:52 PM Page xi

Step 2: The Analysis Phase: Gathering Requirements ........................................336

Use Cases........................................................................................................336

Application Analysis ......................................................................................347

Systems Analysis............................................................................................347

Planning Documents ......................................................................................348

Visualizations..................................................................................................349

Artifacts ..........................................................................................................349

Step 3: The Design Phase ....................................................................................350

What Are the Classes?....................................................................................350

Transformations..............................................................................................352

Other Transformations....................................................................................353

Building the Static Model ..............................................................................354

Dynamic Model..............................................................................................363

Steps 4–6: Implementation, Testing, and Rollout?..............................................366

Iterations ..............................................................................................................367

Summary..............................................................................................................367

Q&A ....................................................................................................................367

Workshop ............................................................................................................368

Quiz ................................................................................................................368

Exercises ........................................................................................................369

12 Implementing Inheritance 371

What Is Inheritance?............................................................................................371

Inheritance and Derivation ............................................................................372

The Animal Kingdom ....................................................................................373

The Syntax of Derivation ..............................................................................374

Private Versus Protected ......................................................................................376

Inheritance with Constructors and Destructors ..................................................378

Passing Arguments to Base Constructors ......................................................381

Overriding Base Class Functions ........................................................................385

Hiding the Base Class Method ......................................................................387

Calling the Base Method................................................................................389

Virtual Methods ..................................................................................................391

How Virtual Functions Work..........................................................................395

Trying to Access Methods from a Base Class................................................396

Slicing ............................................................................................................397

Creating Virtual Destructors ..........................................................................399

Virtual Copy Constructors..............................................................................400

The Cost of Virtual Methods..........................................................................403

Summary..............................................................................................................403

Q&A ....................................................................................................................404

Workshop ............................................................................................................405

xii Sams Teach Yourself C++ in 21 Days, Fifth Edition

00 0672327112_fm.qxd 11/19/04 12:52 PM Page xii

Quiz ................................................................................................................405

Exercises ........................................................................................................405

13 Managing Arrays and Strings 407

What Is an Array?................................................................................................407

Accessing Array Elements..............................................................................408

Writing Past the End of an Array ..................................................................410

Fence Post Errors............................................................................................413

Initializing Arrays ..........................................................................................413

Declaring Arrays ............................................................................................414

Using Arrays of Objects ......................................................................................416

Declaring Multidimensional Arrays ..............................................................417

Initializing Multidimensional Arrays ............................................................419

Building Arrays of Pointers ................................................................................421

A Look at Pointer Arithmetic—An Advanced Topic ..........................................423

Declaring Arrays on the Free Store ....................................................................426

A Pointer to an Array Versus an Array of Pointers ........................................426

Pointers and Array Names..............................................................................427

Deleting Arrays on the Free Store..................................................................429

Resizing Arrays at Runtime............................................................................429

char Arrays and Strings ......................................................................................432

Using the strcpy() and strncpy() Methods......................................................435

String Classes ......................................................................................................436

Linked Lists and Other Structures ......................................................................444

Creating Array Classes ........................................................................................444

Summary..............................................................................................................445

Q&A ....................................................................................................................445

Workshop ............................................................................................................446

Quiz ................................................................................................................446

Exercises ........................................................................................................447

14 Polymorphism 449

Problems with Single Inheritance........................................................................449

Percolating Upward ........................................................................................452

Casting Down ................................................................................................453

Adding to Two Lists ......................................................................................456

Multiple Inheritance ............................................................................................456

The Parts of a Multiply Inherited Object ......................................................460

Constructors in Multiply Inherited Objects....................................................460

Ambiguity Resolution ....................................................................................463

Inheriting from Shared Base Class ................................................................464

Virtual Inheritance..........................................................................................468

Problems with Multiple Inheritance ..............................................................472

Mixins and Capabilities Classes ....................................................................473

Contents xiii

00 0672327112_fm.qxd 11/19/04 12:52 PM Page xiii

Abstract Data Types ............................................................................................473

Pure Virtual Functions....................................................................................477

Implementing Pure Virtual Functions ............................................................478

Complex Hierarchies of Abstraction ..............................................................482

Which Classes Are Abstract? ........................................................................486

Summary..............................................................................................................486

Q&A ....................................................................................................................487

Workshop ............................................................................................................488

Quiz ................................................................................................................488

Exercises ........................................................................................................489

Week 2 In Review 491

Week 3 At a Glance 503

Where You Are Going..........................................................................................503

15 Special Classes and Functions 505

Sharing Data Among Objects of the Same Type: Static Member Data ..............506

Using Static Member Functions ..........................................................................511

Pointers to Functions ..........................................................................................514

Why Use Function Pointers?..........................................................................517

Arrays of Pointers to Functions......................................................................521

Passing Pointers to Functions to Other Functions ........................................523

Using typedef with Pointers to Functions ....................................................525

Pointers to Member Functions ............................................................................528

Arrays of Pointers to Member Functions ......................................................531

Summary..............................................................................................................533

Q&A ....................................................................................................................533

Workshop ............................................................................................................534

Quiz ................................................................................................................534

Exercises ........................................................................................................534

16 Advanced Inheritance 537

Aggregation..........................................................................................................537

Accessing Members of the Aggregated Class................................................545

Controlling Access to Aggregated Members..................................................545

Cost of Aggregation........................................................................................546

Copying by Value ..........................................................................................549

Implementation in Terms of Inheritance Versus Aggregation/Delegation ..........552

Using Delegation ............................................................................................553

Private Inheritance ..............................................................................................562

Adding Friend Classes ........................................................................................571

Friend Functions ..................................................................................................580

xiv Sams Teach Yourself C++ in 21 Days, Fifth Edition

00 0672327112_fm.qxd 11/19/04 12:52 PM Page xiv

Tải ngay đi em, còn do dự, trời tối mất!