1. Trang chủ
  2. » Thể loại khác

Big c++ horstmann 2ndbig c++ horstmann 2nd pdf

1,1K 684 0

Đ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

Định dạng
Số trang 1.090
Dung lượng 16,48 MB

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

Nội dung

This edition has been reorganized to make it more suitable for a course that aims tocover advanced C++ features, data structures, or object-oriented design.. Chapter 2 introduces the sim

Trang 3

The integrated, online

text offers students a

low-cost alternative

to the printed text,

enhanced with direct

students spend more

time practicing, they

come to class better

prepared.

See and try WileyPLUS in action!

Try WileyPLUS with LabRat:

www.wileyplus.com/tours

Why WileyPLUS for Computer Science?

W ileyPLUS for Computer Science is a dynamic online environment that motivates students to spend more

time practicing the problems and explore the material they need to master in order to succeed

Why WileyPLUS for Computer Science?

“I used the homework problems to practice before quizzes and tests I re-did the problems

on my own and then checked WileyPLUS to compare answers.”

— Student Alexandra Leifer, Ithaca College

Trang 4

Students easily access source code for example problems, as well as self-study materials and all the exercises and readings you assign.

All instructional materials, including PowerPoints, illustrations and visual tools, source code, exercises, solutions and gradebook organized in one easy-to-use system

system.

“Overall the WileyPLUS package made the material more

interesting than if it was just a book with no additional material other

than what you need to know.”

— Edin Alic, North Dakota State University

“WileyPLUS made it a lot easier to study I got an A!”

— Student Jeremiah Ellis Mattson, North Dakota State University

Trang 6

SENIOR EDITORIAL ASSISTANT: Carolyn Weisman

MEDIA EDITOR: Lauren Sapira

SENIOR PRODUCTION EDITOR: Ken Santor

SENIOR DESIGNER: Madelyn Lesure

TEXT DESIGNER: Nancy Field

COVER DESIGNER: Howard Grossman

COVER ILLUSTRATOR: Susan Cyr

PRODUCTION MANAGEMENT: Cindy Johnson

This book was set in 10.5/12 Stempel Garamond by Publishing Services and printed and bound by R.R Donnelley – Crawfordsville The cover was printed by R.R Donnelley.

This book is printed on acid-free paper ∞

Copyright © 2009, 2005 John Wiley & Sons, Inc All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permis- sion of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600 Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley and Sons, Inc.,

111 River Street, Hoboken, NJ 07030-5774, (201) 748-6011, fax (201) 748-6008

To order books, or for customer service, please call 1-800-CALL-Wiley (225-5945).

ISBN 978-0-470-38328-5

Printed in the United States of America

10 9 8 7 6 5 4 3 2 1

Trang 7

This book provides a traditional introduction to computer science, focusing on

pro-gram development and effective use of the C++ propro-gramming language It is suitablefor motivated beginners as well as students with prior programming experience Thebook can be used in a variety of settings, such as an introductory computer sciencecourse, a two-semester course sequence that covers data structures and object-oriented design, or an advanced course on C++ and its applications

When writing the book, we were guided by the following principles:

• Teach computer science principles and not just C++ We use the C++ programming

language as a vehicle for introducing computer science concepts, and in this

“Big” book, we cover a large subset of the C++ language However, we do not aim to cover all esoteric aspects of C++ This book focuses on the modern fea-tures of the C++ standard, such as the string class and the STL containers By minimizing the use of error-prone and confusing constructs, your students will learn more computer science and become more productive programmers

• Use a spiral approach to teach complex topics We do not think it is wise to

over-whelm students when we introduce new topics Generally, we start with the essential facts that illustrate a concept, then cover technical details at a later time Here is an example For efficiency’s sake, large object parameters should be passed by constant reference, not by value But that consideration obscures more fundamental issues For that reason, we don’t use constant references when we first introduce classes In the next turn of the spiral, students are comfortable with classes and reference parameters, and a discussion of efficiency is appropri-ate We believe this spiral approach is essential when teaching a language as com-plex as C++

• Introduce C++ as an object-oriented language.Objects are introduced in two

stages From Chapter 2 on, students learn to use objects—in particular, strings,

streams, instances of the simple Time and Employee classes, and graphical shapes Students become comfortable with creating objects and calling member func-tions as the book continues along a traditional path, discussing and providing practice with control structures and functional decomposition In Chapter 5,

Trang 8

students learn how to implement classes and member functions From then on, objects and classes are used as the natural building blocks of computer programs

• Keep the order flexible The book is highly modular Do you prefer to cover arrays

before classes? Simply switch the chapters Do you want to cover streams and files earlier? This is not a problem We supply a graphics library, but it is entirely optional We have found that students enjoy programming exercises in which numbers and visual information reinforce each other But you may not want to spend class time on it Students can read the material on their own, or you can skip it altogether (See Figure 1 on page viii for the chapter dependencies.)

• Offer choices for advanced and applied topics.This “Big” book contains so much material that it would be difficult to cover every chapter, even in an ambitious two-semester course The core material (Part A in Figure 1) contains what is typically covered in a one-semester introductory course: control structures, functions, arrays, classes, inheritance, and stream I/O The advanced material is grouped into four parts to make it easy to choose a focus that fits your course

This edition has been reorganized to make it more suitable for a course that aims tocover advanced C++ features, data structures, or object-oriented design The intro-ductory material has been condensed, and the material on control structures hasbeen consolidated into a single chapter

The advanced chapters are now grouped into four distinct parts:

• Data structures and algorithms

• Advanced C++ and the STL

• Object-oriented design

• Applications

Part B covers an introduction to data structures and algorithms, suitable for a ond-semester programming course Part C focuses on advanced C++ and covers theSTL in detail Part D covers object-oriented design, UML, and design patterns.Finally, Part E (which is available on the Web) contains applied material on graphi-cal user interface programming, databases, and XML that you may find useful as acapstone Except as shown in Figure 1, the parts are independent of each other The web-only chapters are part of the WileyPLUS eBook and may also bedownloaded from the book’s web site at www.wiley.com/college/horstmann If youare interested in adopting a custom print edition that incorporates portions of theonline material, please contact your local Wiley representative

sec-New in This Edition

Streamlined Core Chapters

Modular Design

Trang 9

Preface vii

This book continues to focus on the modern features of the C++ standard, such asthe string class and the STL containers This edition prepares students for thefuture with a new Chapter 21 on the features of the upcoming C++0x standard(included in Part C)

A large number of extended examples and 15 case studies show how C++ tures are used in complete and useful programs

fea-The graphics programming coverage is provided because many students enjoy ing programs that create drawings, and because graphical shapes are splendid exam-ples of objects However, this edition makes it easier to skip this focus if desired Chapter 2 introduces the simple graphics library provided with this book asanother type of object students may program with Thereafter, exercises that makeuse of the graphics library are clearly identified at chapter end An optional Chapter

writ-25 covers graphical user interfaces and the wxWidgets library

The first two pages of this book describe an innovative online tool for teachers andstudents: WileyPLUS WileyPLUS can be adopted with the book, or as an alterna-tive to the printed text for about half the cost of print WileyPLUS integrates all ofthe instructor and student web resources into an online version of this text Formore information and a demo, please visit the web site listed on pages i–ii, or talk toyour Wiley representative (To locate your local representative, visit www.wiley.com/ college and click on “Who’s My Rep”.)

This edition offers enhanced electronic supplements In particular, the test bank hasbeen completely revised to provide a significant number of multiple-choice ques-tions that are suitable for self-check assignments and quizzes

The following resources for students and instructors can be found in the PLUS course for this book Web chapters and source code are also available on theWeb at www.wiley.com/college/horstmann

Wiley-• Solutions to all exercises (for instructors only)

• A test bank (for instructors only)

• A laboratory manual

• Lecture slides that summarize each chapter and include code listings and figures

• Source code for all examples in the book, the Employee and Time classes, and the optional graphics library

• The programming style guide (Appendix A) in modifiable electronic form

• Help with common compilers, the graphics library, and wxWidgets

Trang 10

F i g u r e 1 Chapter Dependencies

4 Functions

5 Classes

14 Operator Overloading

15 Memory Management

20 The Standard Template Library

26 Relational Databases

13 Sets, Maps, &

Priority Queues

18 Name Scope Management

19 Class Hierarchies

21 The C++0x Standard

6 Vectors and Arrays

A: Fundamentals

B: Data Structures & Algorithms

C: Advanced Topics & STL

D: Object-Oriented Design

E: Applications (web only)

25 Graphical User Interfaces

9 Streams

22 Oriented Design

Object-23 The Unified Modeling Language

24 Intro to Design Patterns

E A

Trang 11

Preface ix

This edition builds on the pedagogical elements in the last edition and offers tional aids for the reader Each chapter begins with the customary overview ofchapter objectives and motivational introduction A listing of the chapter contentsthen provides a quick reference to the special features in the chapter

addi-Throughout each chapter, margin notes show where new conceptsare introduced and provide an outline of key ideas These notes aresummarized at the end of the chapter as a chapter review

The program listings are carefully designed for easy reading.Comments are typeset in a separate font that is easier to read than themonospaced “computer” font Functions are set off by a subtle out-line Keywords, strings, and numbers are “color-coded” consistently as they would

be in a development environment (The code for all program listings in the book(plus any additional files needed for each example) is available in the WileyPLUScourse for the book.)

Throughout the chapters, special features set off topics for added flexibility andeasy reference Syntax boxes highlight new syntactical constructs and their purpose

An alphabetical list of these constructs can be found on page xxii

Five additional features, entitled “Common Error”, “Productivity Hint”, ity Tip”, “Advanced Topic”, and “Random Fact”, are identified with the iconsbelow and set off so they don’t interrupt the flow of the main material Some ofthese are quite short; others extend over a page Each topic is given the space that isneeded for a full and convincing explanation—instead of being forced into a one-paragraph “tip” You can use the tables on pages xxiv–xxxi to see the features ineach chapter and the page numbers where they can be found

“Qual-Here is a list of the special features and their icons

• Common Errors describe the kinds of errors that students often make, with an

explanation of why the errors occur, and what to do about them Most students quickly discover the Common Error sections and read them on their own

• Quality Tipsexplain good programming practices Since most of them require an initial investment of effort, these notes carefully motivate the reason behind the advice and explain why the effort will be repaid later

• Productivity Hints teach students how to use their tools more effectively,

familiar-izing them with tricks of the trade such as keyboard shortcuts, global search and replace, or automation of common tasks with scripts

Pedagog ical Structure

Margin notes mark and

reinforce new concepts

and are summarized at

chapter end.

Special Features

Trang 12

• Advanced Topicscover nonessential or more difficult material Some of these ics introduce alternative syntactical constructions that are not necessarily techni-cally advanced In many cases, the book uses one particular language construct but explains alternatives as Advanced Topics Instructors and students should feel free to use those constructs in their own programs if they prefer them It has, however, been our experience that many students are grateful for the “keep it simple” approach, because it greatly reduces the number of gratuitous decisions they have to make.

top-• Random Facts provide historical and social information on computing, as

required to fulfill the “historical and social context” requirements of the ACM curriculum guidelines, as well as capsule reviews of advanced computer science topics

• Appendix A contains a style guide for use with this book We have found it highly beneficial to require a consistent style for all assignments We realize that our style may be different from yours If you have strong feelings about a partic-ular issue, or if this style guide conflicts with local customs, feel free to modify it The style guide is available in electronic form for this purpose

• Appendices B and C contain summaries of the C++ keywords and operators

• Appendix D lists character escape sequences and ASCII character code values

• Appendix E documents all of the library functions and classes used in this book

• Appendices F and G contain a discussion of binary and hexadecimal numbers, and the C++ bit and shift operations

• Appendix H contains a summary of the UML features that are used in this book

• Appendix I compares C++ and Java This appendix should be helpful to students with a prior background in Java

Many thanks to Dan Sayre, Lauren Sapira, Lisa Gee, and Carolyn Weisman at JohnWiley & Sons, and to the team at Publishing Services for their hard work and sup-port for this book project An especially deep acknowledgment and thanks toCindy Johnson, who, through enormous patience and attention to detail, made thisbook a reality

Several individuals assisted in the creation of the online resources for this edition

We would like to thank Kurt Schmidt, Drexel University, and Diya Biswas, Maria

Kolakowska, and John O’Meara for a great set of lecture slides We are grateful to

Fred Annexstein, University of Cincinnati, Steven Kollmansberger, South Puget Sound Community College, and Gwen Walton, Florida Southern College, for their

Appendices

Acknowledgments

Trang 13

Preface xi

contributions to the solutions And thank you to John Russo, Wentworth Institute

of Technology, for working with us to prepare the labs that accompany the book.

We are very grateful to the many individuals who reviewed this and the prior tion of the book, made many valuable suggestions, and brought an embarrassinglylarge number of errors and omissions to our attention They include:

edi-Charles Allison, Utah Valley State College

Vladimir Akis, California State University, Los Angeles

Richard Borie, University of Alabama, Tuscaloosa

Ramzi Bualuan, Notre Dame University

Drew Coles, Boston University

Roger DeBry, Utah Valley State College

Joseph DeLibero, Arizona State University

Martin S Dulberg, North Carolina State University

Jeremy Frens, Calvin College

Timothy Henry, University of Rhode Island

Robert Jarman, Augusta State University

Jerzy Jaromczyk, University of Kentucky

Debbie Kaneko, Old Dominion University

Vitit Kantabutra, Idaho State University

Stan Lippman, Microsoft Corporation

Brian Malloy, Clemson University

Stephen Murrell, University of Miami

Jeffery Popyack, Drexel University

John Russo, Wentworth Institute of Technology

Kurt Schmidt, Drexel University

William Shay, University of Wisconsin, Green Bay

Joseph R Shinnerl, University of California, Los Angeles

Deborah Silver, Rutgers University

John Sterling, Polytechnic University

Gwen Walton, Florida Southern College

Joel Weinstein, New England University

Lillian Witzke, Milwaukee School of Engineering

Our gratitude also to those who took time to tell us about their C++ course andwhose advice shaped this new edition:

Fred Annexstein, University of Cincinnati

Noah D Barnette, Virginia Tech

Stefano Basagni, Northeastern University

Trang 14

Peter Breznay, University of Wisconsin, Green Bay Subramaniam Dharmarajan, Arizona State University Stephen Gilbert, Orange Coast College

Barbara Guillott, Louisiana State University Mir Behrad Khamesee, University of Waterloo Sung-Sik Kwon, North Carolina Central University

W James MacLean, University of Toronto Ethan V Munson, University of Wisconsin, Milwaukee Kurt Schmidt, Drexel University

Michele A Starkey, Mount Saint Mary College William Stockwell, University of Central Oklahoma Jonathan Tolstedt, North Dakota State University David P Voorhees, Le Moyne College

Salih Yurttas, Texas A&M University

Trang 15

1.3 The Anatomy of a Computer 4

1.4 Translating Human-Readable Programs to Machine Code 9

1.5 Programming Languages 10

1.6 The Evolution of C++ 11

1.7 Becoming Familiar with Your Computer 12

1.8 Compiling a Simple Program 15

Trang 16

3.6 The while Loop 121

3.7 The for Loop 125

Trang 17

5.6 Constructors with Parameters 244

5.7 Accessing Data Fields 249

5.8 Comparing Member Functions with Nonmember Functions 250

5.9 Separate Compilation 253

6.1 Using Vectors to Collect Data Items 266

6.2 Working with Vectors 269

6.3 Vector Parameters and Return Values 275

6.4 Removing and Inserting Vector Elements 277

6.5 Arrays 280

7.1 Pointers and Memory Allocation 306

7.2 Deallocating Dynamic Memory 311

7.3 Common Uses for Pointers 314

7.4 Arrays and Pointers 322

7.5 Pointers to Character Strings 327

7.6 Pointers to Functions 330

8.1 Derived Classes 342

8.2 Calling the Base-Class Constructor 349

8.3 Overriding Member Functions 350

Trang 18

9.1 Reading and Writing Text Files 376

9.2 The Inheritance Hierarchy of Stream Classes 379

11.2 Profiling the Selection Sort Algorithm 448

11.3 Analyzing the Performance of the Selection Sort Algorithm 449

12.2 Implementing Linked LIsts 476

12.3 The Efficiency of List and Vector Operations 490

12.4 Queues and Stacks 493

Trang 19

14.2 Case Study: Fractional Numbers 551

14.3 Overloading Simple Arithmetic Operators 558

14.4 Overloading Comparison Operators 560

14.5 Overloading Input and Output 562

14.6 Overloading Increment and Decrement Operators 564

14.7 Overloading the Assignment Operators 568

14.8 Overloading Conversion Operators 569

14.9 Overloading the Subscript Operator 572

14.10 Overloading the Function Call Operator 574

14.11 Case Study: Matrices 577

15.6 Case Study: Matrices, Continued 627

Trang 20

16.1 Template Functions 642

16.2 Compile-Time Polymorphism 647

16.3 Template Classes 649

16.4 Turning a Class into a Template 652

16.5 Nontype Template Parameters 655

16.6 Setting Behavior Using Template Parameters 656

16.7 Case Study: Matrices, Continued 659

17.1 Handling Exceptional Situations 666

17.2 Alternative Mechanisms for Handling Exceptions 668

18.8 Case Study: Matrices, Continued 720

19.1 Class Inheritance Hierarchies 728

Trang 21

20.6 Case Study: Dijkstra’s Shortest Algorithm 771

20.7 Functions, Generators, and Predicates 775

20.8 Generic Algorithms 781

20.9 Iterator Adapters 791

20.10 Case Study: File Merge Sort 792

21.1 C++0x Design Objectives 806

21.2 Automatic Type Inference 807

21.3 Range-based for Loop 808

21.4 New Constructor Features 810

21.10 Other Minor Changes 820

22.1 The Software Life Cycle 826

22.7 Case Study: Printing an Invoice 839

22.8 Case Study: An Educational Game 851

Trang 22

23.1 The Unified Modeling Language 876

24.2 The Pattern Concept 914

24.3 The A DAPTER Pattern 919

24.4 The T EMPLATE M ETHOD Pattern 922

24.5 Function Objects and the S TRATEGY Pattern 925

24.6 The C OMPOSITE Pattern 928

24.7 Case Study: Putting Patterns to Work 931

25.1 The wxWidgets Toolkit

25.10 Case Study: A GUI for the Clock Game

26.1 Organizing Database Information

26.2 Queries

26.3 Installing a Database

26.4 Database Programming in C++

26.5 Case Study: Accessing an Invoice Database

Chapter25 Graphical User Interfaces

Chapter26 Relational Databases

Trang 23

Contents xxi

27.1 XML Tags and Documents

27.2 Parsing XML Documents

27.3 Creating XML Documents

27.4 Document Type Definitions

27.5 Parsing with Document Type Definitions

Trang 24

Array Initializer List Construction 812

Array Variable Definition 282

Constructor with Base-Class Initializer 350

Constructor with Field Initializer List 248

Member Function Call 64

Member Function Definition 239

Multiple Inheritance 738

Name Space Alias 719

Name Space Definition 718

Nested Class Definition 713

new Expression 309

Alphabetical List of Syntax Boxes

Trang 25

Special Features xxiii

Object Construction 69

Object Variable Definition 70

Output Statement 34

Overloaded Operator Definition 548

Overloaded Operator Member Function Definition 550

Pointer Dereferencing 309

Pointer Variable Definition 309

Private Inheritance 716

Protected Members 707

Pure Virtual Member Function 731

Range-based for Loop 809

Reference Parameter 180

return Statement 171

Simple Program 18

Template Class Concept Binding 819

Template Class Definition 651

Template Function Concept Binding 818

Template Function Definition 644

Template Member Function Definition 652

Trang 26

Chapter Common Errors Quality Tips

1 Introduction Omitting Semicolons 19

Misspelling Words 21

2 Numbers and Objects Buffered Input 42

Failed Input 44 Roundoff Errors 49 Integer Division 58 Unbalanced Parentheses 59 Forgetting Header Files 60 Trying to Call a Member Function Without an Object 73

Initialize Variables When You Define Them 36 Choose Descriptive Variable

Do Not Use Magic Numbers 53 White Space 61 Factor Out Common Code 61

3 Control Flow Confusing = and == 107

Comparison of Point Numbers 108 The Dangling else Problem 112 Multiple Relational Operators 117 Confusing && and ||

Floating-Conditions 118 Infinite Loops 123 Off-by-One Errors 124 Forgetting a Semicolon 129

Brace Layout 103 Compile with Zero

Warnings 107 Use for Loops for Their

Intended Purpose Only 128 Don’t Use != to Test the End

of a Numeric Range 128 Symmetric and

Asymmetric Bounds 130 Count Iterations 130

4 Functions Missing Return Value 171

Type Mismatch 173

Use Meaningful Names for Parameters 173 Minimize Global Variables 185 Keep Functions Short 188

5 Classes Mixing >> and getline Input 230

Forgetting a Semicolon 234 const Correctness 240 Forgetting to Initialize All Fields

in a Constructor 246 Trying to Reset an Object by Calling a Constructor 247

File Layout 252

6 Vectors and Arrays Bounds Errors 272

Omitting the Column Size of

a Two-Dimensional Array Parameter 292

Don’t Combine Vector Access and Index Increment 273 Make Parallel Vectors into Vectors of Objects 279 Name the Array Size and

Capacity Consistently 291

Trang 27

Table of Special Features xxv

Backup Copies 14 The ENIAC and the Dawn

of Computing 8 Standards Organizations 12

Numeric Ranges and Precisions 38 Casts 49 Combining Assignment

and Arithmetic 50 Enumerated Types 54 Remainder of Negative Integers 61 Characters and C Strings 66

The Pentium Floating-Point

of a Stream 137

Artificial Intelligence 120 The Denver Airport Luggage Handling System 138

Write Functions with Reuse

The Explosive Growth of Personal Computers 181 The Therac-25 Incidents 202 The First Bug 205

Calling Constructors from Constructors 247 Overloading 248

Programmer Productivity 243 Programming—Art or Science? 257

Inspecting Vectors in the

Debugger 272

Strings Are Vectors

of Characters 273 Passing Vectors by Constant Reference 277

An Early Internet Worm 274 International Alphabets 292

Trang 28

Chapter Common Errors Quality Tips

7 Pointers Confusing Pointers with the

Data to Which They Point 310 Declaring Two Pointers on the Same Line 310 Dangling Pointers 312 Memory Leaks 313 Confusing Array and Pointer Declarations 325 Returning a Pointer to a

Local Array 325 Failing to Allocate Memory 328 Confusing Character

Pointers and Arrays 329 Copying Character Pointers 329

Program Clearly, Not Cleverly 324

8 Inheritance Private Inheritance 348

Attempting to Access Private Base-Class Fields 355 Forgetting the Base-Class

Slicing an Object 363

9 Streams

10 Recursion Infinite Recursion 415

Tracing Through Recursive Functions 419

11 Sorting and Searching

12 Lists, Queues, and Stacks

13 Sets, Maps, and Priority Queues

14 Operator Overloading Inconsistent Operations 566

Only One Level of Conversion 571 Ambiguous Conversions 571

Avoid Dependencies on Order

of Evaluation 565 Conversion, Coercion, and Casts 570

Trang 29

Table of Special Features xxvii

The this Pointer 310 The Address Operator 313 References 319 Using a Pointer to Step

Through an Array 323 Dynamically Allocated Arrays 326

Electronic Voting Machines 320 Embedded Systems 332

Protected Access 356 Virtual Self-Calls 364

Operating Systems 364

Binary Files 398 Encryption Algorithms 392

Databases and Privacy 399

The Limits of Computation 434

The Quicksort Algorithm 457 Defining an Ordering for

Overload Operators Only

to Make Programs Easier

The First Algorithm 557

Trang 30

Chapter Common Errors Quality Tips

15 Memory Management Forgetting the Dual Use of Single

Argument Constructors 605 Default Constructor and

Parentheses 607 Confusing Destruction and Deletion 615 Not Declaring Destructors Virtual 617 Self Assignment 626 Reference Counting Fails in the Presence of Cycles 627

Avoid Buffer Overflow Errors 597 When to Use the System-Defined Copy Constructor 609 Observing Constructors 612 Include Virtual Destructors 618

If Destructor, Then Copy Constructor and Assignment 619

16 Templates Invalid Type Parameters 645

Templates Don’t Preserve Inheritance 654

Move from Concrete to Abstract 646 Document Template Parameter Requirements 655

17 Exception Handling Forgetting to Check Return

Values 671 Throwing Objects versus

Throwing Pointers 682 Exceptions During Construction

of Global Variables 686

Nobody Cares How Fast You Get the Wrong Answer 669 Tie Exception Classes to the Standard Library 681 Use Exceptions for Exceptional Cases 687 Throwing an Exception is Not

a Sign of Shame 688

18 Name Scope Management Confusing Scope and Lifetime 704 Don’t Pollute the Global Scope 703

Use Accessor Functions for Protected Access to Data 708 Friendship is Granted,

Not Taken 710 Manage Encapsulation 713 Use Unambiguous Names for Name Spaces 719

19 Class Hierarchies Taking Type of Pointer,

Not Object 734 Using Type Tests Instead of Polymorphism 734 Failing to Preserve the Is-a Relationship 738

Avoid Multiple Inheritance 742 Design Your Own Software Frameworks 745

20 The Standard Template Library Mismatched Iterators 756

Assuming the Ending Iterator

Is Included in a Range 756 Forgetting to Erase Removed Elements 790

Experimentally Evaluate Execution Times 761

Trang 31

Table of Special Features xxix

Tracing Execution 616 Constructors Are Always

Extensions 611 Overloading the Memory

Management Operators 621

Templates and Overloading 648 Forms of Polymorphism 648 Nested Templates 654

The Ariane Rocket Incident 688

Overriding, Shadowing, and Scopes 702 Forward References 705 Local Name Space Declaration 719

A Forest, Not a Tree 730 Virtual Function Tables 735

Functional Programming 745

Memory Allocation Traits 765

Trang 32

Chapter Common Errors Quality Tips

21 Features of the C++0x Standard

23 The Unified Modeling Language

24 An Introduction to Design

Patterns

Confusing Function Objects and Classes 927 Pattern Recognition 930

25 Graphical User Interfaces

26 Relational Databases Joining Tables Without

Specifying a Link Condition 15

27 XML XML Describes Structure, Not

Appearance 4 XML Elements Describe Data Fields, Not Classes 23

XML Is Stricter Than HTML 3 Prefer XML Elements over

Attributes 8 Avoid Children with Mixed Elements and Text 9 Stand on the Shoulders of Others 23

Trang 33

Table of Special Features xxxi

Programming Languages 820

Extreme Programming 830

Generic Programming with Inheritance and Templates 918

Learning About a New Toolkit 6

Becoming Familiar with a

Complex Tool 7

Custom Dialog Boxes 30 Visual Programming 41

Stick with the Standard 4

Avoid Unnecessary Data

Helper Functions in an

XML Parser 22

Writing an XML Document 30

Use DTDs with Your XML Files 43

The XML Schema Specification 36 Other XML Technologies 43

Word Processing and Typesetting Systems 4 Grammars, Parsers, and

Compilers 10

Trang 35

1

Introduction

To understand the activity of programming

To learn about the architecture of computers

To learn about machine languages and higher-level

programming languages

To become familiar with your compiler

To compile and run your first C++ program

To recognize syntax and logic errors

To understand the notion of an algorithm

CH A P T E R GO A L S

This chapter contains a brief introduction to the architecture of computers and anoverview of programming languages You will learn about the activity ofprogramming: how to write and run your first C++ program, how to diagnose and

fix programming errors, and how to plan your programming activities

Trang 36

C HAPTER C ONTENTS

You have probably used a computer for work or fun Many peopleuse computers for everyday tasks such as balancing a checkbook orwriting a term paper Computers are good for such tasks They canhandle repetitive chores, such as totaling up numbers or placingwords on a page, without getting bored or exhausted

More importantly, the computer presents the checkbook or the term paper onthe screen and lets you fix mistakes easily Computers make good game machinesbecause they can play sequences of sounds and pictures, involving the human user

in the process

What makes all this possible is not only the computer The puter must be programmed to perform these tasks One programbalances checkbooks; a different program, probably designed and con-structed by a different company, processes words; and a third programplays a game The computer itself is a machine that stores data (numbers, words,pictures), interacts with devices (the monitor, the sound system, the printer), andexecutes programs Programs are sequences of instructions and decisions that thecomputer carries out to achieve a task

com-Today’s computer programs are so sophisticated that it is hard to believe thatthey are composed of extremely primitive operations A typical operation may beone of the following

• Put a red dot at this screen position

• Get a number from this location in memory

Computers execute very

basic operations in rapid

1.3 The Anatomy of a Computer 4

R ANDOM F ACT 1.1: The ENIAC and the Dawn

R ANDOM F ACT 1.2: Standards Organizations 12

1.7 Becoming Familiar with Your Computer 12

P RODUCTIVITY H INT 1.1: Backup Copies 14

1.8 Compiling a Simple Program 15

S YNTAX 1.1: Simple Program 18

C OMMON E RROR 1.1: Omitting Semicolons19

1.9 Errors 19

C OMMON E RROR 1.2: Misspelling Words 21

1.10 The Compilation Process 21

1.11 Algorithms 24

Trang 37

1.2 • What Is Programming? 3

• Add up these two numbers

• If this value is negative, continue the program at a certain instruction

The computer user has the illusion of smooth interaction because a program tains a huge number of such operations, and because the computer can execute them

con-at grecon-at speed

The flexibility of a computer is quite an amazing phenomenon The samemachine can balance your checkbook, print your term paper, and play a game Incontrast, other machines carry out a much narrower range of tasks; a car drives and

a toaster toasts Computers can carry out a wide range of tasks because they executedifferent programs, each of which directs the computer to work on a specific task

A computer program tells a computer, in minute detail, the sequence

of steps that are needed to fulfill a task The act of designing andimplementing these programs is called computer programming Inthis book, you will learn how to program a computer—that is, how

to direct the computer to execute tasks

To use a computer you do not need to do any programming When you write aterm paper with a word processor, that program has been programmed by the man-ufacturer and is ready for you to use That is only to be expected—you can drive acar without being a mechanic and toast bread without being an electrician Mostpeople who use computers every day never need to do any programming

Since you are reading this introductory computer science book, it may well beyour career goal to become a professional computer scientist or software engineer.Programming is not the only skill required of a computer scientist or software engi-neer; indeed, programming is not the only skill required to create successful com-puter programs Nevertheless, the activity of programming is central to computerscience It is also a fascinating and pleasurable activity that continues to attract andmotivate bright students The discipline of computer science is particularly fortu-nate that it can make such an interesting activity the foundation of the learning path

To write a computer game with motion and sound effects or a word processorthat supports fancy fonts and pictures is a complex task that requires a team ofmany highly skilled programmers Your first programming efforts will be moremundane The concepts and skills you learn in this book form an important founda-tion, and you should not be disappointed if your first programs do not rival thesophisticated software that is familiar to you Actually, you will find that there is animmense thrill even in simple programming tasks It is an amazing experience to seethe computer carry out a task precisely and quickly that would take you hours ofdrudgery, to make small changes in a program that lead to immediate improve-ments, and to see the computer become an extension of your mental powers

Trang 38

To understand the programming process, you need to have a rudimentary standing of the building blocks that make up a computer We will look at a personalcomputer Larger computers have faster, larger, or more powerful components, butthey have fundamentally the same design.

under-At the heart of the computer lies the central processing unit (CPU) (see Figure 1) It consists of a single chip, or a small number of chips.

A computer chip (integrated circuit) is a component with a plastic ormetal housing, metal connectors, and inside wiring made principallyfrom silicon For a CPU chip, the inside wiring is enormously compli-cated For example, the Pentium chip (a popular CPU for personal computers at thetime of this writing) is composed of several million structural elements, called

transistors.

Figure 2 shows a magnified detail view of a CPU chip The CPUperforms program control, arithmetic, and data movement That is,the CPU locates and executes the program instructions; it carries outarithmetic operations such as addition, subtraction, multiplication,and division; it fetches data from external memory or devices andstores data back All data must travel through the CPU whenever it

is moved from one location to another (There are a few technicalexceptions to this rule; some devices can interact directly with memory.)

The computer stores data and programs in memory There are two kinds of memory Primary storage is fast but expensive; it is made from memory chips: so-called random-access memory (RAM) and read-only memory (ROM) Read-only memory contains certain pro-

grams that must always be present—for example, the code needed to

The central processing

unit (CPU) executes one

operation at a time

F i g u r e 1 Central Processing Unit

Data values can be

brought into the CPU for

processing from storage

or from input devices

such as the keyboard,

Trang 39

1.3 • The Anatomy of a Computer 5

start the computer Random-access memory might have been better called write memory”, because the CPU can read data from it and write data back to it.That makes RAM suitable to hold changing data and programs that do not have to

“read-be available permanently RAM memory has two disadvantages It is comparatively

expensive, and it loses all its data when the power is turned off Secondary storage, usually a hard disk (see Figure 3), provides less expensive storage that persists with-

out electricity A hard disk consists of rotating platters, which are coated with amagnetic material, and read/write heads, which can detect and change the magneticflux on the platters Programs and data are typically stored on the hard disk andloaded into RAM when the program starts The program then updates the data inRAM and writes the modified data back to the hard disk

F i g u r e 2 CPU Chip Detail

TRANSFER CACHE

SYSTEM BUS

DYNAMIC EXECUTION DYNAMIC

EXECUTION

DYNAMIC EXECUTION

RAPID EXECUTION ENGINE

Trang 40

The central processing unit, RAM memory, and the electronics controlling thehard disk and other devices are interconnected through a set of electrical lines called

a bus Data travels along the bus from the system memory and peripheral devices to the CPU and back Figure 4 shows a motherboard, which contains the CPU, the

RAM, and card slots, through which cards that control peripheral devices connect

to the bus

F i g u r e 3 A Hard Disk

F i g u r e 4 A Motherboard

Ngày đăng: 18/05/2017, 10:55

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w