1. Trang chủ
  2. » Công Nghệ Thông Tin

Contents i What’s New with This Edition Teach Yourself ANSI C++ in 21 Days, Premier Edition, is

875 463 1
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Contents i What’s New with This Edition Teach Yourself ANSI C++ in 21 Days, Premier Edition, is
Tác giả Jesse Liberty, J. Mark Hord
Trường học S MS Publishing
Chuyên ngành Computer Science
Thể loại book
Năm xuất bản 1996
Thành phố Indianapolis
Định dạng
Số trang 875
Dung lượng 5,88 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

When a program is compiled, the time-consuming task of translating the source code into machinelanguage has already been accomplished.. The word program is used in two ways: to describe

Trang 1

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

What’s New with This Edition

Teach Yourself ANSI C++ in 21 Days, Premier Edition, is a new edition of the international bestseller, Teach Yourself C++ in 21 Days This Premier Edition offers

more than just 21 days of learning ANSI/ISO C++

Major changes throughout this edition have been made to reflect the latest ANSI/ISO C++ draft standard In addition, seven new lessons, referred to as “Bonus Days,”have been added to provide you with additional information for creating moresophisticated programs The Bonus Day lessons are not required reading in orderfor you to learn to program in C++ As a matter of fact, on the very first day you willwrite a simple C++ program

On Bonus Day 22, “Advanced C++ Features,” you learn to use a collection ofspecialized ANSI C++ tools that many programmers don’t even realize exist Thesetools are not essential for every C++ programmer to know but are indispensable inmany circumstances

Bonus Day 23, “More About Streams,” covers some of the more advanced streamsprogramming techniques After completing this lesson, you will have all you need

to create new manipulators for the stream classes you learn to create on Day 16 Youwill also learn a great deal about other streams programming techniques that spacewould not allow us to cover on Day 16

On Bonus Day 24, “Object-Oriented Design,” you learn more about this importantsubject Without object-oriented design techniques, C++ is “just another C” withfew advantages over its predecessor This lesson helps you think in a way that builds

on the object-oriented design paradigm

Bonus Days 25 and 26, “Data Structures” and “Simple Sorting and SearchingAlgorithms,” respectively, introduce you to the inner sanctum of computer science

On these two days you learn how to solve several common categories of problems

“Common Mistakes and Basic Debugging,” on Bonus Day 27, is designed to helpyou avoid some of the common mistakes that many beginning programmers make.Not all errors can be avoided, but with this lesson you should more quickly recognizemany errors by their categories and more quickly find their solutions

The final day of the bonus week, “What’s Next?,” gives you some insight on where

to turn when you run into a question that this book doesn’t seem to answer It alsoprovides the resources you need to further improve your C++ programming skills

Trang 2

Teach Yourself ANSI C++ in 21 Daysii

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

Trang 3

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

teach yourself

ANSI C++

in 21 days, Premier Edition

Trang 4

Teach Yourself ANSI C++ in 21 Daysiv

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

Trang 6

Teach Yourself ANSI C++ in 21 Daysvi

Technical Reviewer

Justin Bell John W Charlesworth

SA Springer, Tim Taylor, Andrew Stone, Mark Walchle Todd Wente, Colleen Williams

Copyright 1996 by Sams Publishing

PREMIER EDITION

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

responsi-bility for errors or omissions Neither is any liaresponsi-bility assumed for damages

resulting from the use of the information contained herein For

informa-tion, address Sams Publishing, 201 W 103rd St., Indianapolis, IN 46290.

International Standard Book Number: 0-672-30887-6

Library of Congress Catalog Card Number: 95-72920

99 98 97 96 4 3 2 1

Interpretation of the printing code: the rightmost double-digit number is

the year of the book’s printing; the rightmost single-digit, the number of the

book’s printing For example, a printing code of 96-1 shows that the first

printing of the book occurred in 1996.

Composed in Agaramond and MCPdigital by Macmillan Computer Publishing

Printed in the United States of America

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.

Publisher and President Richard K Swadley

Acquisitions Manager Greg Wiegand

Managing Editor Cindy Morrow

Marketing Manager Gregg Bushyeager

Trang 7

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

Overview

21 Working with Multiple Files for Large Programs 609

Trang 8

Teach Yourself ANSI C++ in 21 Daysviii

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

Bonus Days At A Glance 635

Trang 9

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

Contents

A Note to C Programmers 2

Where You Are Going 2

Day 1 Getting Started 3 A Brief History of C++ 3

ANSI/ISO C++ 5

What Is a Program? 5

Sophisticated Tools for Sophisticated Programming 6

Procedural, Structured, and Object-Oriented Programming 6

C++ and Object-Oriented Programming 8

How C++ Evolved 9

Should I Learn C First? 10

Preparing to Program 10

Your Development Environment 11

Compiling the Source Code 12

Creating an Executable File with the Linker 12

The Development Cycle 13

HELLO.CPP: Your First C++ Program 14

Compile Errors 15

Summary 16

Q&A 16

Quiz 17

Exercises 17

2 The Parts of a C++ Program 19 The Parts of a Simple Program 19

A Brief Look at cout 21

Comments 22

Types of Comments 23

Using Comments 23

Comments at the Top of Each File 24

A Final Word of Caution About Comments 25

Functions 26

Using Functions 27

Summary 29

Q&A 29

Quiz 29

Exercises 30

Trang 10

Teach Yourself ANSI C++ in 21 Days x

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

3 Variables and Constants 31

What Is a Variable? 31

Setting Aside Memory 32

Size of Integers 33

Signed and Unsigned 34

Fundamental Variable Types 35

Defining a Variable 36

Case Sensitivity 37

Keywords 38

Creating More Than One Variable at a Time 39

Assigning Values to Your Variables 39

typedef 40

Choosing Between short and long 41

Wrapping Around in Unsigned Integers 42

Wrapping Around a Signed Integer 43

Characters 43

chars and Numbers 44

Special Printing Characters 44

Constants 46

Literal Constants 46

Symbolic Constants 46

Enumerated Constants 49

Summary 50

Q&A 51

Quiz 52

Exercises 53

4 Expressions and Statements 55 Statements 56

Whitespace 56

Blocks and Compound Statements 57

Expressions 57

Operators 59

Assignment Operator 59

Mathematical Operators 60

Integer Division and Modulus 60

Combining the Assignment and Mathematical Operators 61

Increment and Decrement 62

Prefix and Postfix 62

Precedence 64

Nesting Parentheses 64

The Bitwise Operators 65

Operator AND 66

Operator OR 67

Operator Exclusive OR 67

Trang 11

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

The Complement Operator 67

Shift Operators 67

Setting Bits 67

Clearing Bits 68

Flipping Bits 68

Fast Math Through the Power of the Bit 68

The Nature of Truth 69

Relational Operators 69

The if Statement 70

else 73

Advanced if Statements 75

Using Braces in Nested if Statements 76

Logical Operators 79

Logical AND 79

Logical OR 80

Logical NOT 80

Relational Precedence 80

More About Truth and Falsehood 81

Conditional (Ternary) Operator 82

Summary 84

Q&A 84

Quiz 85

Exercises 85

5 Functions 87 What Is a Function? 88

Declaring and Defining Functions 88

Declaring the Function 89

Function Prototypes 89

Defining the Function 91

Execution of Functions 93

Local Variables 93

Global Variables 95

More on Local Variables 97

Function Statements 99

Function Arguments 99

Using Functions as Parameters to Functions 99

Parameters Are Local Variables 100

Return Values 101

Default Parameters 103

Overloading Functions 106

Special Topics 108

Inline Functions 109

Recursion 111

Summary 114

Q&A 114

Trang 12

Teach Yourself ANSI C++ in 21 Days xii

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

Quiz 115

Exercises 115

Extra Credit 116

How Functions Work 117

Levels of Abstraction 117

Partitioning RAM 117

The Stack and Functions 120

6 Basic Classes 123 Creating New Types 124

Why Create a New Type? 124

Classes and Members 124

Declaring a Class 125

Classes Versus Objects 126

Defining an Object 126

Accessing Class Members 126

Assign to Objects, Not to Classes 126

If It’s Not Declared, Your Class Won’t Have It 127

Private Versus Public 128

Make Member Data Private 130

Privacy Versus Security 132

Implementing Class Methods 134

Constructors and Destructors 136

Default Constructors and Destructors 137

const Member Functions 140

Interface Versus Implementation 141

Where to Put Class Declarations and Method Definitions 143

Inline Implementation 145

Classes with Other Classes as Member Data 147

Structures 150

Why Two Keywords Do the Same Thing 151

Summary 152

Q&A 152

Quiz 153

Exercises 154

7 More Program Flow 155 Looping 156

The Roots of Looping goto 156

Why goto Is Shunned 157

while Loops 157

More Complicated while Statements 159

continue and break 160

The while (true) Loop 163

do…while Loops 164

The do…while Loop 165

Trang 13

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

for Loops 167

Advanced for Loops 169

Empty for Loops 172

Nested Loops 173

Scoping in Loops 174

Summing Up Loops 174

switch Statements 177

Using a switch Statement with a Menu 180

Summary 183

Q&A 183

Quiz 184

Exercises 184

Week 1 In Review 187 Week In Review 192

Week 2 At A Glance 193 Where You Are Going 193

Day 8 Pointers 195 What Is a Pointer? 195

Storing the Address in a Pointer 197

The Indirection Operator 199

Pointers, Addresses, and Variables 200

Manipulating Data by Using Pointers 201

Examining the Address 202

Why Would You Use Pointers? 204

The Stack and the Free Store 204

new 206

delete 206

Memory Leaks 208

Creating Objects on the Free Store 209

Deleting Objects 210

Accessing Data Members 211

Member Data on the Free Store 212

The this Pointer 213

Stray or Dangling Pointers 215

const Pointers 218

const Pointers and const Member Functions 218

const this Pointers 220

Summary 220

Q&A 221

Quiz 221

Exercises 221

9 References 223 What Is a Reference? 223

Requesting the Address of a Reference 225

Trang 14

Teach Yourself ANSI C++ in 21 Days xiv

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

What Can Be Referenced? 228

Null Pointers and Null References 230

Passing Function Arguments by Reference 230

Making swap() Work with Pointers 231

Implementing swap() with References 233

Understanding Function Headers and Prototypes 234

Returning Multiple Values 235

Returning Values by Reference 237

Passing by Reference for Efficiency 238

Passing a const Pointer 241

References as an Alternative 243

Choosing Between References and Pointers 245

Pointer References 246

Mixing References and Pointers 248

Don’t Return a Reference to an Object that Isn’t in Scope! 249

Returning a Reference to an Object on the Heap 251

Who Has the Pointer? 253

Summary 253

Q&A 254

Quiz 254

Exercises 254

10 Advanced Functions 257 Overloaded Member Functions 257

Using Default Values 260

Choosing Between Default Values and Overloaded Functions 262

The Default Constructor 262

Overloading Constructors 263

Initializing Objects 264

The Copy Constructor 265

Operator Overloading 270

Writing an Increment Function 271

Overloading the Prefix Operator 272

Returning Types in Overloaded Operator Functions 273

Returning Nameless Temporaries 274

Using the this Pointer 276

Overloading the Postfix Operator 277

operator+ 279

Overloading operator+ 281

Issues in Operator Overloading 282

Limitations on Operator Overloading 283

What to Overload 283

operator= 284

Conversion Operators 286

Operator unsigned short() 288

Trang 15

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

Summary 289

Q&A 290

Quiz 291

Exercises 291

11 Arrays 293 What Is an Array? 293

Array Elements 294

Writing Past the End of an Array 295

Fence Post Errors 298

Initializing Arrays 298

Declaring Arrays 299

Arrays of Objects 301

Multidimensional Arrays 302

Initializing Multidimensional Arrays 303

A Word About Memory 304

Arrays of Pointers 305

Declaring Arrays on the Free Store 306

A Pointer to an Array Versus an Array of Pointers 307

Pointers and Array Names 307

Deleting Arrays on the Free Store 309

char Arrays 310

strcpy() and strncpy() 312

String Classes 313

Linked Lists and Other Structures 320

Array Classes 325

Summary 326

Q&A 327

Quiz 327

Exercises 328

12 Inheritance 329 What Is Inheritance? 329

Inheritance and Derivation 330

The Animal Kingdom 331

The Syntax of Derivation 331

Private Versus Protected Class Members 333

Constructors and Destructors 335

Passing Arguments to Base Constructors 337

Overriding Functions 341

Hiding the Base Class Method 343

Calling the Base Method 345

Virtual Methods 346

You Can’t Get There from Here 351

Slicing 351

Virtual Destructors 353

Virtual Copy Constructors 354

The Cost of Virtual Methods 357

Trang 16

Teach Yourself ANSI C++ in 21 Days xvi

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

Summary 357

Q&A 358

Quiz 359

Exercises 359

13 Multiple Inheritance 361 Problems with Single Inheritance 361

Percolating Upward 365

The Parts of a Multiple Inheritance Object 368

Constructors in Multiple Inheritance Objects 369

Ambiguity Resolution 371

Inheriting from a Shared Base Class 372

Virtual Inheritance 376

Problems with Multiple Inheritance 379

Mixins and Capabilities Classes 380

Abstract Data Types 381

Pure Virtual Functions 384

Implementing Pure Virtual Functions 385

Complex Hierarchies of Abstraction 389

Which Types Are Abstract? 392

Summary 393

Q&A 393

Quiz 394

Exercises 394

14 Special Classes and Functions 395 Static Member Data 395

Static Member Functions 400

Pointers to Functions 402

Why Use Function Pointers? 406

Arrays of Pointers to Functions 408

Passing Pointers to Functions to Other Functions 410

Using typedef with Pointers to Functions 412

Pointers to Member Functions 413

Arrays of Pointers to Member Functions 415

Summary 417

Q&A 418

Quiz 418

Exercises 419

Week 2 In Review 421 Week 3 At A Glance 431 Where You Are Going 431

Day 15 Advanced Inheritance 433 Containment 433

Accessing Members of the Contained Class 439

Trang 17

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

Filtering Access to Contained Members 439

Cost of Containment 440

Copying by Value 442

Delegation Versus Implemented in Terms of 443

Delegation 444

Private Inheritance 449

Friend Classes 453

friend Functions 460

friend Functions and Operator Overloading 460

Overloading the Insertion Operator 463

Summary 465

Q&A 465

Quiz 466

Exercises 466

16 Streams 469 Overview of Streams 469

Encapsulation 470

Buffering 471

Streams and Buffers 473

Standard I/O Objects 474

Redirection 474

Input Using cin 475

Strings 476

String Problems 477

operator>> Returns a Reference to an istream Object 479

Other Member Functions of cin 480

Single Character Input 480

Getting Strings from Standard Input 482

Using cin.ignore() 485

peek() and putback() 486

Output with cout 487

Flushing the Output 487

Related Functions 488

Manipulators, Flags, and Formatting Instructions 489

Using cout.width() 490

Setting the Fill Characters 491

Set Flags 491

Streams Versus the printf() Function 493

File Input and Output 495

ofstream 495

Condition States 496

Opening Files for Input and Output 496

Changing the Default Behavior of ofstream on Open 498

Binary Versus Text Files 500

Command-Line Processing 502

Trang 18

Teach Yourself ANSI C++ in 21 Days xviii

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

Summary 505

Q&A 506

Quiz 506

Exercises 507

17 The Preprocessor 509 The Preprocessor and the Compiler 509

Seeing the Intermediate Form 510

Using #define 510

Using #define for Constants 510

Using #define for Tests 511

The #else Precompiler Command 511

The #error Directive 512

The #pragma Directive 513

Inclusion and Inclusion Guards 513

Defining on the Command Line 514

Undefining 514

Conditional Compilation 516

Macro Functions 516

Why All the Parentheses? 517

Macros Versus Functions and Templates 519

Inline Functions 519

String Manipulation 521

Stringizing 521

Concatenation 521

Predefined Macros 522

assert() 522

Debugging with assert() 524

assert() Versus Exceptions 524

Side Effects 525

Class Invariants 525

Printing Interim Values 529

Debugging Levels 531

Summary 534

Q&A 535

Quiz 535

Exercises 536

18 Creating Reusable Code 537 Remember Code Reuse 538

Avoid Literal Constants 538

Encapsulate the Details 539

Comment on the Logic 539

Remember Code Maintenance 541

The Power of Seven 541

Document the Initial Code and Changes 541

Develop a Consistent Coding Style 542

Develop a Maintenance Strategy 545

Trang 19

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

Remember Code Portability 546

Adhere to the ANSI/ISO Standard 547

Think Globally 548

Summary 549

Q&A 549

Quiz 550

Exercises 550

19 Templates 551 What are Templates? 551

Parameterized Types 552

Template Definition 552

Using the Name 554

Implementing the Template 554

Template Functions 558

Templates and Friends 558

Nontemplate Friend Classes and Functions 559

General Template Friend Class or Function 561

A Type-Specific Template Friend Class or Function 563

Using Template Items 564

Specialized Functions 567

Static Members and Templates 573

The Standard Template Library 575

Summary 576

Q&A 577

Quiz 578

Exercises 578

20 Exceptions and Error Handling 581 Bugs, Errors, Mistakes, and Code Rot 582

Exceptions 583

A Word About Code Rot 583

Preparing for Exceptions With C++ 584

How Exceptions Are Used 584

Using try Blocks and catch Blocks 589

Catching Exceptions 590

More Than One catch Specification 590

Exception Hierarchies 593

Data in Exceptions and Naming Exception Objects 594

Exceptions and Templates 600

Exceptions Without Errors 603

Bugs and Debugging 603

Breakpoints 604

Watch Points 604

Examining Memory 604

Assembler 605

Trang 20

Teach Yourself ANSI C++ in 21 Days xx

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

Summary 605

Q&A 605

Quiz 606

Exercises 607

21 Working With Multiple Files for Large Programs 609 Basic Concepts 610

Header Files 610

Precompiled Header Files 612

Variable Names and Function Prototypes 613

Implementation Files and Variable Scope 613

Interdependency of Variables Between Files 615

More About extern 618

Hiding Variables and Global Scope Resolution 618

Avoiding Multiple Declarations 620

Summary 621

Q&A 621

Quiz 622

Exercises 622

Week 3 In Review 625 Bonus Week At A Glance 635 Day 22 Advanced C++ Features 637 Namespaces and Class Libraries 638

Namespaces 638

Class Library Design 640

How Polymorphism Works 643

Casting and Run-Time Type Identification 644

Const Cast 645

Dynamic Cast 646

Static Cast 649

Reinterpret Cast 650

Type Info 651

Explicit Constructors 651

Data Alignment and Assembly Language 652

Packing Data by Understanding Data Alignment 653

Spiking with Assembly Language 653

Summary 654

Q&A 655

Quiz 655

Exercises 656

23 More About Streams 659 The Streams Hierarchy 659

Using istrstream 660

Trang 21

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

Using ostrstream 662

Stream Position 663

Format Specification Flags 664

Creating Manipulators and Custom Stream Operators 664

Multiple Streams 667

Summary 671

Q&A 671

Quiz 672

Exercises 672

24 Object-Oriented Design 673 What OOD Is Not 673

Structured Programming 674

Structured Programming Drawbacks 674

OOD Steps 675

Identify the Objects 675

Identify the Methods 676

Establish the Visibility 677

Establish the Interface 677

Implement the Objects 678

Maintain or Iterate the Design 678

Other OOD Descriptions 679

When Not to Use OOD 679

Summary 680

Q&A 681

Quiz 681

Exercises 681

25 Data Structures 683 Looking Back at Arrays 683

Queues and Stacks 684

A Simple Queue Example 684

A Simple Stack Example 688

Trees 689

Summary 698

Q&A 698

Quiz 699

Exercises 699

26 Simple Sorting and Searching 701 Sorting 702

The Bubble Sort 703

The Selection Sort 706

The Shell Sort 707

The Quick Sort 710

Sorting Disk Files 712

Trang 22

Teach Yourself ANSI C++ in 21 Daysxxii

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

Searching 712The Straightforward String Search 712The Binary Search 714Summary 717Q&A 717Quiz 718Exercises 718

27 Common Mistakes and Basic Debugging 721

Class Explosion 721Boundary Violations and Off-by-One Errors 725Increment and Decrement Errors 726Pointer Problems 726Bracket or Parenthesis Mismatch 727Test and Assignment Confusion 728Debugging Tips 728Asking for Help 729Summary 729Q&A 730Quiz 730Exercises 731

28 What’s Next? 733

The Standard Libraries 734String 735Localization Library 735Containers, Iterators, and Algorithms 735Bit Fields and Bitset 736Numerics Library 737Next Steps 737Sharpening Your Skills 737Other Great Books 737Magazines 738Internet and the World Wide Web 738Electronic Mail 739Summary 739Q&A 739Quiz 740

Appendixes

A Operator Precedence 741

B C++ Keywords 745

Trang 23

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

C Binary and Hexadecimal 747

Other Bases 748Around the Bases 749Binary 750Why Base 2? 751Bits, Bytes, and Nibbles 751Binary Numbers 752Hexadecimal 752

D Answers 757

Day 1 758Quiz 758Exercises 758Day 2 758Quiz 758Exercises 759Day 3 760Quiz 760Exercises 761Day 4 761Quiz 761Exercises 762Day 5 764Quiz 764Exercises 765Day 6 767Quiz 767Exercises 768Day 7 770Quiz 770Exercises 771Day 8 772Quiz 772Exercises 773Day 9 774Quiz 774Exercises 775Day 10 777Quiz 777Exercises 778Day 11 782Quiz 782Exercises 782Day 12 783Quiz 783Exercises 784

Trang 24

Teach Yourself ANSI C++ in 21 Daysxxiv

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

Day 13 785Quiz 785Exercises 786Day 14 787Quiz 787Exercises 788Day 15 793Quiz 793Exercises 794Day 16 798Quiz 798Exercises 799Day 17 800Quiz 800Exercises 801Day 18 803Quiz 803Exercises 804Day 19 805Quiz 805Exercises 806Day 20 810Quiz 810Exercises 811Day 21 816Quiz 816Exercises 816Day 22 818Quiz 818Exercises 819Day 23 821Quiz 821Exercises 822Day 24 823Quiz 823Exercises 823Day 25 824Quiz 824Exercises 824Day 26 826Quiz 826Exercises 827Day 27 828Quiz 828Exercises 829Day 28 830Quiz 830

Trang 25

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

Acknowledgments

I would like to acknowledge the many people who contributed to this book, both directly andindirectly First and foremost, Stacey and Robin Liberty, whose support, encouragement,and patience made it possible Also, Mike Kraley, Ed Belove, and Patrick Johnson, who create

an intellectual atmosphere at the Interchange Online Network, which makes it a gas to come

to work every day, and the many, many developers at Ziff from whom I learned whatever it

is I know about C++

I must particularly acknowledge those who taught me how to program, Skip Gilbrech andDavid McCune, and those who taught me C++, including Steve Rogers and especially StevenZagieboylo Others who contributed directly or indirectly to this book include Scott Boag,David Bogartz, Gene Broadway, Drew and Al Carlson, Frank Childs, Jim Culbert, FranDaniels, Thomas Dobbing, James Efstratiou, June Goldstein, Basha Goldstein-Weiss,Michael Griffin, David Heath, Eric Helliwell, Gisele and Ed Herlihy, Mushtaq Khalique,Matt Kingman, Steve Leland, Sangam Pant, Mike Rothman, Michael Smith, Frank Tino,Seth Weiss, Donovan White, Mark Woodbury, and Alan Zeitchek Special thanks go toWayne Wylupski and Steven Zagieboylo

Programming is as much a business and creative experience as it is a technical one, and I musttherefore acknowledge Tom Hottenstein, Jay Leve, David Rollert, David Shnaider, andRobert Spielvogel I also want to thank the many people at Sams Publishing who worked

so hard to create this book If any of what I’ve written is especially clear, it is thanks to theeditors

Finally, I’d like to thank Mrs Kalish, who taught my sixth-grade class how to do binaryarithmetic in 1965, when neither she nor we knew why

—Jesse Liberty

The first people that come to mind are my family They’ve been there through thick and thin,shared my enthusiasm and bore the brunt of my frustrations Praise God for their love anddevotion

Maggie, if I had to do it all again, I’d still say “I do.” Timmy, you’re everything I couldever want for a son; I’m very proud Heather, thank you for your kindness and gentle spirit,and for always loving Daddy even when he was cranky Alicia, though you are small, yourlove has always been big; you have been a wonderful daughter Amber, thank you for yourgift of joy and fun that helped me keep focus on the things that really matter

—J Mark Hord

Trang 26

Teach Yourself ANSI C++ in 21 Daysxxvi

P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3

About the Authors

Jesse Liberty

Jesse Liberty has been programming computers professionally for more than 11 years He is

a Software Architect at AT&T Interchange Online Network where he was a foundingmember of the Software Development Team He is also president of The Liberty Group,Inc., and a former vice president of Citibank’s Development Division Jesse lives with hiswife, Stacey, and his daughter, Robin, in the suburbs of Cambridge, Massachusetts He can

be reached via the Internet at jl@Ichange.com, or as jl on Interchange

J Mark Hord

J Mark Hord is a C++ programmer for Musicam USA He has worked in the computerindustry since his first exposure while enlisted in the U.S Navy submarine fleet Hisexperience spans both commercial and defense companies Mark lives in New Jersey with hiswife and four children

Trang 27

P2/V3/sqc3 TY ANSI C++ in 21 30887-6 andy 2.21.95 AAG1 LP#3

As you prepare for your first week of learning how to program in ANSI C++, you

will need a few things: a compiler, an editor, and this book If you don’t have a

C++ compiler and an editor, you can still use this book, but you won’t get as much

out of it as you would if you were to do the exercises

The best way to learn to program is by writing programs! At the end of each day

you will find a quiz and some exercises Be sure to take the time to answer all the

questions and to evaluate your work as objectively as you can The later lessons

build on the lessons in the earlier lessons, so be sure you fully understand the

material before moving on

Trang 28

P2/V3/sqc3 TY ANSI C++ in 21 30887-6 andy 2.21.95 AAG1 LP#3

Week 1

A Note to C Programmers

The material in the first five days will be familiar to you Be sure to skim the material and to

do the exercises, to make sure you are fully up to speed before going on to Day 6 If you havehad some exposure to C++ but not object-oriented programming, you might want to skipahead and skim through Bonus Days 23 and 24 after Day 5 If you’re convinced that C++

is simply a “better C” and nothing else, then you’ll miss the point altogether To be a goodC++ programmer, you have to break out of the design paradigm used in C programming andstart thinking in objects

Where You Are Going

The first week covers the material you need to get started with programming in general, andwith C++ in particular Day 1, “Getting Started” and Day 2, “The Parts of the Program,”introduce you to the basic concepts of programming and program flow On Day 3, “Variablesand Constants,” you learn about variables and constants and how to use data in yourprograms On Day 4, “Expressions and Statements,” you learn how programs branch, based

on the data provided and the conditions encountered when the program is running On Day

5, “Functions,” you learn what functions are and how to use them, and on Day 6, “BasicClasses,” you learn about classes and objects Day 7, “More Program Flow,” teaches moreabout program flow, and by the end of the first week, you will be writing real object-orientedprograms

Trang 29

P2/V3/sqc4 TY ANSI C++ in 21 30887-6 andy 2.22.96 CH01 LP#3

1

Getting Started

Welcome to Teach Yourself ANSI C++ in 21 Days, Premier Edition! Today you

will get started on your way to becoming a proficient C++ programmer You’ll

learn the following topics:

■ Why C++ is the emerging standard in software development

■ The steps to develop a C++ program

■ How to enter, compile, and link your first working C++ program

A Brief History of C++

Computer languages have undergone dramatic evolution since the first

elec-tronic computers were built to assist in telemetry calculations during World

War II Early on, programmers worked with the most primitive computer

instructions, machine language These instructions were represented by long

strings of ones and zeros Soon, assemblers were invented to map machine

instructions to humanly readable and manageable mnemonics, such as ADD and

MOV

1

Week

Trang 30

In time, higher-level languages evolved, such as BASIC and COBOL These enabled people

to work with something approximating words and sentences, such as Let I = 100 Theseinstructions were translated back into machine language by interpreters and compilers Aninterpreter translates a program as it reads it, turning the programmer’s program instructions,

or code, directly into actions Compilers translate the code into an intermediary form This step is called compiling, and produces an object file The compiler then invokes a linker, which

turns the object file into an executable program Most modern compilers and linkers aredesigned to work together as a team, and the transition between the two is invisible to theprogrammer

Because interpreters read the code as it is written and execute the code on the spot, they areeasy for the programmer to work with Compilers introduce the extra steps of compiling andlinking the code, which are inconvenient, but they produce a program that runs faster When

a program is compiled, the time-consuming task of translating the source code into machinelanguage has already been accomplished

Another advantage of many compiled languages is that you can distribute the executableprogram to people who don’t have the compiler With an interpretive language, you musthave the interpreter to run the program

For many years, the principal goal of computer programmers was to write short pieces of codethat would execute quickly The program needed to be small because memory was expensive,and it needed to be fast because processing power was also expensive As computers havebecome smaller, cheaper, and faster, and as the cost of memory has fallen, these priorities havechanged Today the cost of a programmer’s time far outweighs the cost of most of thecomputers in use by businesses Well-written, easy to maintain code is at a premium “Easy

to maintain” means that as business requirements change, the program can be extended andenhanced without great expense

In the 1970s, some programmers at AT&T were working to develop tools that would maketheir jobs easier One of the members of that team, Dennis Ritchie, created a new compiled

language and called it C C became popular partially because it provided low-level ality, along with a high-level control structure A computer language is said to be a high-level

function-language if it hides the details of the computer architecture from the programmer and is

referred to as a low-level language if it does not Because C did not fit either category well, it became known as a medium-level language.

In the late 1980s, more and more computer scientists began to change the way theyapproached problems, and they began to realize that the languages they were using did notfit well with their new problem-solving paradigm Yet, because C was so popular, many wereunwilling to throw out all the old in order to start solving problems differently Instead, newversions of C began to appear that were designed with the new paradigm as their measure.Bjarne Stroustrup at AT&T invented one of those new versions of the C language Mr.Stroustrup’s new C language became known as C++

Trang 31

P2/V3/sqc4 TY ANSI C++ in 21 30887-6 andy 2.22.96 CH01 LP#3

1

ANSI/ISO C++

Programming languages, much like human languages, tend to change with time and even

diversify into various dialects Programmers have to learn the local version of a particular

language wherever they happen to work, only to have to learn a different version at the next

job Employers have to spend time training new programmers for the programming language

eccentricities at their company So it benefits many to strive to standardize computer

languages and limit the extent of those differences These concerns are part of the drive for

a single programming language for the United States Department of Defense, which gave

birth to the programming language, Ada

Similar concerns caused a push for the ANSI C standard some years ago Today, there is an

international effort to standardize the C++ language between the American National

Standards Institute (ANSI) and the International Standards Organization (ISO)

commit-tees The purpose of this effort, in the words of the draft standard, is “to promote portability,

reliability, maintainability, and efficient execution of C++ language programs on a variety of

computing systems.” Though the ANSI/ISO C++ standard is currently in draft form and not

yet approved as final, future changes to the draft should be minor for the most part In Teach

Yourself ANSI C++ in 21 Days we attempt to document the C++ language as it is defined in

the ANSI/ISO draft at the time of this writing

Because the ANSI/ISO standard is still in a state of change, compilervendors have not fully implemented it in their products Compilersimplement the draft standard in varying degrees, so shop around Thismeans that there might be some programs in this book that you cannotuse with your compiler

You can obtain a copy of the latest ANSI/ISO C++ draft and other useful C++ information

through the C++ Virtual Library World Wide Web (WWW) site at

http://info.desy.de/user/projects/C++.html

What Is a Program?

The word program is used in two ways: to describe individual instructions, or source code,

created by the programmer; and to describe an entire piece of executable software This

distinction can cause enormous confusion, so we will try to distinguish between the source

code on one hand, and the executable on the other

W ARNING

Trang 32

A program can be defined either as a set of written instructions created by a

programmer or as an executable piece of software

Source code can be turned into an executable program in two ways: Interpreters translate thesource code into computer instructions, and the computer acts on those instructionsimmediately Alternatively, compilers translate source code into a program that you can run

at a later time Although interpreters are easier to work with, most serious programming isdone with compilers because compiled code runs much faster C++ is a compiled language

Sophisticated Tools for Sophisticated

Programming

The problems programmers are asked to solve have been changing Twenty years ago,programs were created to manage large amounts of raw data The people writing the code andthe people using the program were all computer professionals Today, computers are in use

by far more people, and many know very little about how computers and programs work.These people are more interested in using computers to solve their business problems anddon’t want using the computer to get in the way of doing that

Ironically, in order to become easier to use for this new audience, programs have become farmore sophisticated Gone are the days when users typed in cryptic commands at esoteric

prompts, only to see a stream of raw data Today’s programs use sophisticated user-friendly interfaces involving multiple windows, menus, dialog boxes, and all the myriad metaphors

with which we’ve all become familiar The programs written to support this new approachare far more complex than those written just 10 years ago

As programming requirements have changed, both languages and the techniques used forwriting programs have evolved Although the complete history is fascinating, the part thatconcerns us is the transformation from procedural programming to object-oriented pro-gramming

Procedural, Structured, and Object-Oriented Programming

Until recently, programs were thought of as a series of procedures that acted upon data A

procedure, or function, was a set of specific computer instructions executed one after the

other The data was quite separate from the procedures, and the trick in programming was

to keep track of which functions called which other functions, and what data was changed

It was considered good programming practice to isolate data and the functions or proceduresthat operated on them To make sense of this potentially confusing situation, structuredprogramming was created

N EW T ERM

Trang 33

P2/V3/sqc4 TY ANSI C++ in 21 30887-6 andy 2.22.96 CH01 LP#3

1

A computer function or procedure is a logical collection of instructions for performing

one part of the problem being solved by the computer program A program is the

whole; a procedure or function is one part in that whole

The principal idea behind structured programming is as simple as the idea of divide and

conquer A computer program can be thought of as consisting of a set of tasks Any task that

is too complex to be described simply is broken down into a set of smaller component tasks,

until the tasks are sufficiently small and self-contained so that they can be easily understood

As an example, computing the average salary of every employee of a company is a rather

complex task You can, however, break it down into these subtasks:

1 Find out what each person earns

2 Count how many people you have

3 Total all the salaries

4 Divide the total by the number of people you have

Totaling the salaries can, itself, be broken down into more simple tasks:

1 Get each employee’s record

2 Access the salary

3 Add the salary to the running total

4 Get the next employee’s record

In turn, obtaining each employee’s record can be broken down into simpler steps as well:

1 Open the file of employees

2 Find the employee’s data in the file

3 Read the data from disk

Structured programming remains an enormously successful approach for dealing with

complex problems By the late 1980s, however, some of its deficiencies became all too clear

First, the separation of data from the tasks that manipulate the data became harder and harder

to comprehend and maintain It is natural to think of your data (employee records, for

example) and what you can do with your data (sort, edit, and so on) as related ideas

Second, programmers often had difficulty structuring a program to solve a problem while

solving the problem at the same time It was a classic inability to see the forest for the trees

Instead of solving problems, they often spent their time reinventing new ways to fit the

problem to the structure

N EW T ERM

Trang 34

The way we are now using computers—with menus and buttons and windows—fosters a

more interactive, event-driven approach to computer programming Event-driven means

that an event happens (the user presses a button or chooses from a menu), and the programmust respond Programs are becoming increasingly interactive, making it important todesign for that kind of functionality

Old-fashioned programs forced the user to proceed step-by-step through a series of

screens Modern event-driven programs present all the choices at once and respond

to the user’s actions

Object-oriented programming attempts to respond to these needs, providing techniques formanaging enormous complexity, achieving reuse of software components, and coupling datawith the tasks that manipulate that data

The essence of object-oriented programming is to treat data and the procedures that act upon

the data as a single object—a self-contained entity with an identity and certain characteristics

of its own

C++ and Object-Oriented Programming

C++ fully supports oriented programming, including the four pillars of

object-oriented development: encapsulation, data hiding, inheritance, and polymorphism.

Encapsulation and Data Hiding

Encapsulation and data hiding are object-oriented design techniques that programmers canuse to make interchangeable software parts The goal behind these techniques is to build self-contained objects that can be used as parts in a variety of programs Now, instead ofspecialized functions and procedures that work on a narrow collection of data, we can buildobjects that can be used to build larger objects To accomplish interchangeability, underlyingdata inside the object must be hidden so that it cannot be accidentally changed in anunexpected way Another reason for data hiding is to allow programmers to use an objectwithout needing to know all the details about how the object does what it does

The property of being a self-contained unit is called encapsulation The fact that the encapsulated unit can be used without regard to how it works is called data hiding.

When a radio enthusiast builds a radio and needs a volume control, she doesn’t create a newvolume control from scratch Instead, she simply pulls a volume control from a shelf in hergarage or at the local electronics store All the properties of the control are encapsulated inthe control object; they are not spread out through the circuits It is not necessary tounderstand how the volume control works in order to use it effectively; its data is hiddeninside its casing

N EW T ERM

N EW T ERM

Trang 35

P2/V3/sqc4 TY ANSI C++ in 21 30887-6 andy 2.22.96 CH01 LP#3

1

C++ supports the properties of encapsulation and data hiding through the creation of

user-defined types, called classes You’ll see how to create classes on Day 6, “Basic Classes.” After

it is created, a well-defined class acts as a fully encapsulated entity It is used as a whole unit

The actual inner workings of the class should be hidden; users of a well-defined class do not

need to know how the class works They just need to know how to use it

Inheritance and Reuse

When the engineers at Acme Motors want to build a new car, they have two choices: They

can start from scratch, or they can modify an existing model Perhaps their Star model is

nearly perfect, but they want to add a turbocharger and a six-speed transmission The chief

engineer would prefer not to start from the ground up, but rather to say, “Let’s build another

Star, but let’s add these additional capabilities We’ll call the new model a Quasar.” A Quasar

is a kind of Star, but one with new features A Quasar inherits all that a Star is and has

additional features, as well

As with other fields of engineering, software engineers have invented a name for the design

technique of making new objects from old They call this design technique inheritance The

initial object in this technique is called the base object, and the new object is called a derived

object The Quasar is derived from the Star, and thus inherits all its qualities, but it can add

to them as needed Inheritance and its application in C++ is discussed on Day 12,

“Inheritance” and Day 15, “Advanced Inheritance.”

Inheritance, in computer science, is the creation of new objects from other objects

that are similar The new object is said to inherit all that the original object contains.

The new Quasar might respond differently than a Star does when you press down on the

accelerator The Quasar might engage fuel injection and a turbocharger, while the Star would

simply let gasoline into its carburetor A user, however, does not have to know about these

differences; she can just “floor it,” and the right thing will happen depending on which car

she’s driving

How C++ Evolved

Since Bjarne Stroustrup created C++ less than a decade ago, it has gone from being used by

only a handful of developers at AT&T to being the programming language of choice for an

estimated one million developers worldwide It is expected that, by the end of the decade,

C++ will be the predominant language for commercial software development

Although it is true that C++ is a superset of C, and that virtually any legal C program is a legal

C++ program, the leap from C to C++ is very significant C++ benefited from its relationship

to C for many years because C programmers could ease into their use of C++ To really get

the full benefit of C++, however, many programmers found they had to unlearn much of what

N EW T ERM

Trang 36

Should I Learn C First?

The question inevitably arises: Because C++ is a superset of C, should you learn C first?Stroustrup and most other C++ programmers agree that not only is it unnecessary to learn

C first, but it might be advantageous not to do so This book attempts to meet the needs ofpeople like you, who come to C++ without prior experience of C In fact, this book assumes

no programming experience of any kind

Preparing to Program

C++, perhaps more than other languages, demands that the programmer design the programbefore writing it Trivial problems, such as the ones discussed in the first few lessons of thisbook, don’t require much design However, complex problems, such as the ones professionalprogrammers are challenged with every day, do require design; and the more thorough thedesign, the more likely it is that the program will solve the problems it is designed to solve,

on time and on budget A good design also makes for a program that is relatively bug-free andeasy to maintain It has been estimated that fully 90 percent of the cost of software is thecombined cost of debugging and maintenance To the extent that good design can reducethose costs, it can have a significant impact on the bottom-line cost of the project.The first question you need to ask when preparing to design any program is, “What is theproblem I’m trying to solve?” Every program should have a clear, well-articulated goal, andyou’ll find that even the simplest programs in this book do so

The second question every good programmer asks is, “Can this be accomplished withoutresorting to writing custom software?” Reusing an old program, using pen and paper, orbuying software off the shelf are often better solutions to a problem than writing somethingnew The programmer who can offer these alternatives will never suffer from lack of work;finding less expensive solutions to today’s problems will always generate new opportunitieslater

Assuming you understand the problem, and it requires writing a new program, you are ready

to begin your design

Trang 37

P2/V3/sqc4 TY ANSI C++ in 21 30887-6 andy 2.22.96 CH01 LP#3

1

Your Development Environment

This book makes the assumption that your computer has a mode in which you can write

directly to the screen, without worrying about a graphical environment such as the ones in

Windows or on the Macintosh

Your compiler might have its own built-in text editor, or you might be using a commercial

text editor or word processor that can produce text files The important thing is that whatever

you write your program in, it must save simple, plain-text files with no word processing

commands embedded in the text Examples of safe editors include the Windows Notepad,

the DOS Edit command, Brief, Epsilon, EMACS, and vi Many commercial word

processors, such as WordPerfect, Word, and dozens of others, also offer a method for saving

simple text files

The files you create with your editor are called source files, and for C++, they typically are

named with the extension cpp, cp, or c In this book, all source code files are named with

the cpp extension, but check your compiler documentation for what it needs

Most C++ compilers don’t care what extension you give your sourcecode, but if you don’t specify otherwise, many will use cpp by default

Don’t Do

DO use a simple text editor to create your source code, or use the built-in editor

that comes with your compiler

DON’T use a word processor that saves special formatting characters If you do use

a word processor, save the file as ASCII text

DO save your files with the c, cp, or cpp extension.

DO check your documentation for specifics about your compiler and linker to

ensure that you know how to compile and link your programs

N OTE

Trang 38

Compiling the Source Code

Although the source code in your file may seem cryptic in the beginning, and anyone who

doesn’t know C++ will struggle to understand what it is for, it is still in what is called readable form Your source code file is not an executable program, so you cannot run it like

human-you can human-your word processor program

To turn your source code into an executable program, you use a compiler How you invokeyour compiler, and how you tell it where to find your source code, will vary from compiler

to compiler; check your documentation

After your source code is compiled, an object file is produced This file is often named withthe extension obj This is still not an executable program, however To turn this into anexecutable program, you must run your linker

Creating an Executable File with the

Linker

C++ programs are typically created by linking one or more obj files with one or more

libraries A library is a collection of linkable files that you created, that were supplied with

your compiler, or that you purchased separately All C++ compilers come with a library ofuseful functions—or procedures—and classes that you can include in your program Afunction is a block of code that performs a service, such as adding two numbers or printing

to the screen A class is a collection of data and related functions; we’ll be talking about classes

a lot, starting on Day 5, “Functions.” Libraries are the general-purpose, reusable objects youcan use for building more specialized objects We will be using an ANSI-defined standard set

of libraries throughout this book

A library is a reusable collection of data and functions, typically entire object

definitions, that you can use as interchangeable parts in your programs They are notcomplete in themselves, and they may have additional parts in them that your program doesnot use However, they are provided as general solutions to typical problems that program-mers like you have needed to solve in the past

The steps to create an executable file are as follows:

1 Create a source code file with a cpp extension

2 Compile the source code into a file with the obj extension

3 Link your obj file with any needed libraries to produce an executable program

N EW T ERM

Trang 39

P2/V3/sqc4 TY ANSI C++ in 21 30887-6 andy 2.22.96 CH01 LP#3

1

The Development Cycle

If every program worked the first time you tried it, that would be the complete development

cycle: Write the program, compile the source code, link the program, and run it

Unfortu-nately, almost every program—no matter how trivial—can and will have errors, or bugs, in

it Some bugs cause the compile to fail, some cause the link to fail, and some only show up

when you run the program

Whatever the type of bug you find, you must fix it This involves editing your source code,

recompiling and relinking, and then rerunning the program This cycle is represented in

Figure 1.1, which diagrams the steps in the development cycle

Compile

Compile Errors

Link

Link Errors

?

Run Program

Time Errors

Trang 40

HELLO.CPP: Your First C++ Program

Traditional C programming books begin by writing the words Hello World to the screen, or

a variation on that statement This time-honored tradition is carried on here

Type the first program directly into your editor, exactly as shown When you are certain it

is correct, save the file, compile it, link it, and run it It will print the words Hello World toyour screen Don’t worry too much about how it works; this is really just to get youcomfortable with the development cycle Every aspect of this program will be covered overthe next couple of days

The listings in this book contain line numbers on the left Thesenumbers are for reference within the book They should not be typedinto your editor For example, in line 1 of Listing 1.1, you should enterthe following:

5: cout << “Hello World!\n”;

6: }

Make sure you enter this exactly as shown The only typing liberty you should take right now

is to enter any number of spaces or tabs you prefer before the cout on line 5 Pay carefulattention to the special characters The double less-than arrow symbol (<<) in line 5 is the

redirection symbol, produced on most keyboards by holding the shift key and pressing the

comma key twice Line 5 ends with a semicolon; don’t leave this off !Also, check to make sure you are following your compiler directions properly Mostcompilers link automatically, but check your documentation If you get errors, look over yourcode carefully and determine how it is different from Listing 1.1 If you see an error on line

1, such as cannot find file iostream.h, check your compiler documentation for directions

on setting up your include path or environment variables If you receive an error that there

is no prototype for main, add the line void main(); just before line 3 You need to add thisline to every program in this book before the beginning of the main function Most compilersdon’t require this, but a few do

W ARNING

TYPE

Ngày đăng: 20/10/2013, 17:15

TỪ KHÓA LIÊN QUAN

🧩 Sản phẩm bạn có thể quan tâm