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

Walter savitch absolute c++

969 478 0
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 đề Walter Savitch Absolute C++
Tác giả Walter Savitch
Trường học Pearson Education
Chuyên ngành Computer Science
Thể loại Textbook
Năm xuất bản 2008
Thành phố United States of America
Định dạng
Số trang 969
Dung lượng 21,68 MB

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

Nội dung

Đây là quyển sách tiếng anh về lĩnh vực công nghệ thông tin cho sinh viên và những ai có đam mê. Quyển sách này trình về lý thuyết ,phương pháp lập trình cho ngôn ngữ C và C++.

Trang 2

SavitchC++.book Page i Monday, February 12, 2007 2:38 PM

Trang 4

SavitchC++.book Page iii Monday, February 12, 2007 2:38 PM

Trang 5

Publisher Greg TobinExecutive Editor Michael HirschAcquisitions Editor Matt GoldsteinManager, Product Development Pat MahtaniEditorial Assistant Maurene GooAssociate Managing Editor Jeffrey HolcombText and Cover Design Joyce Cosentino WellsDigital Assets Manager Marianne GrothSenior Media Producer Bethany TiddSenior Marketing Manager Michelle BrownMarketing Assistant Sarah MilmoreSenior Manufacturing Buyer Carol MelvilleProduction Coordination Chris Norton, Argosy PublishingComposition and Illustrations Argosy Publishing

Cover Image© Brand XMany of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and Addison-Wesley was aware of a trademark claim, the designations have been printed in initial caps or all caps

The interior of this book was composed in Adobe FrameMaker

Library of Congress Cataloging-in-Publication DataSavitch, Walter J., 1943-

Absolute C++ / Walter Savitch 3rd ed

p cm

Includes bibliographical references and index

ISBN-13: 978-0-321-46893-2ISBN-10: 0-321-46893-7

1 C++ (Computer program language) I Title

QA76.73.C153S279 2007005.13’3 dc22

2007004477Copyright © 2008 Pearson Education, 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, or otherwise, without the prior written permission of the publisher Printed in the United States of America For information on obtaining permission for use

of material in this work, please submit a written request to Pearson Education, Inc., Rights and Contracts Department, 75 Arlington Street, Suite 300, Boston, MA 02116, fax your request to 617-848-7047,

or e-mail at http://www.pearsoned.com/legal/permissions.htm

ISBN-13: 978-0-321-46893-2ISBN-10: 0-321-46893-7

1 2 3 4 5 6 7 8 9 10—CRW—11 10 09 08 07

Trang 6

Preface

This book is designed to be a textbook and reference for programming in the C++ guage Although it does include programming techniques, it is organized around thefeatures of the C++ language, rather than any particular curriculum of programmingtechniques The main audience I had in mind were undergraduate students who hadnot had extensive programming experience with the C++ language As such the bookwould be a suitable C++ text or reference for a wide range of users The beginningchapters are written at a level that is accessible to beginners, while the boxed sections

lan-of those chapters serve to introduce more experienced programmers to basic C++ tax Later chapters are also accessible, but are written at a level suitable for studentswho have progressed to these more advanced topics (For those who want a textbookwith more pedagogical material and more on very basic programming technique, try

syn-Problem Solving with C++: The Object of Programming, Sixth Edition, ley.) Absolute C++ is also suitable for anyone learning the C++ language on their own

Addison-Wes-The C++ coverage in this book goes well beyond what a beginner needs to know Inparticular, it has extensive coverage of inheritance, polymorphism, exception handling,and the Standard Template Library (STL), as well as basic coverage of patterns and theunified modeling language (UML)

CHANGES IN THIS EDITION

If you have not used the second edition of this text, you can skip this subsection Ifyou have used the second edition, this subsection will tell you how this third editiondiffers from the second

For instructors, the transition from the second to this third edition is easy You canteach the same course, presenting the same topics in the same order with essentially nochanges in the material covered or the chapters assigned The changes to this editionconsist exclusively of supplementary material added to the chapters of the previousedition Additional new programing examples and programming projects have beenadded at various places in the text Coverage of hash tables with chaining and a settemplate class have been added to Chapter 17 Additional material on doubly linkedlists has also been added to Chapter 17 In Chapter 19 iterator declaration have beenrewritten for greater compatibility with common C++ compilers Coverage of the mapcontainer template class has also been added to Chapter 19

Trang 7

vi Preface

STANDARD TEMPLATE LIBRARY

The Standard Template Library (STL) is an extensive collection of preprogrammeddata structure classes and algorithms The STL is perhaps as big a topic as the coreC++ language, so I have included a substantial introduction to STL There is a fullchapter on the general topic of templates and a full chapter on the particulars of STL,

as well as other material on, or related to, STL at other points in the text

OBJECT-ORIENTED PROGRAMMING

This book is organized around the structure of C++ As such, the early chapters coveraspects of C++ that are common to most high-level programming languages but are notparticularly oriented toward object-oriented programming (OOP) programming For areference book, and for a book for learning a second language, this makes sense How-ever, I consider C++ to be an OOP language If you are programming in C++ and not

C, you must be using the OOP features of C++ This text offers extensive coverage ofencapsulation, inheritance, and polymorphism as realized in the C++ language Thefinal chapter, on patterns and UML, gives additional coverage of OOP-related material

FLEXIBILITY IN TOPIC ORDERING

This book allows instructors wide latitude in reordering the material This is tant if a book is to serve as a reference This is also in keeping with my philosophy ofaccommodating the instructor’s style, rather than tying the instructor to my own per-sonal preference of topic ordering Each chapter introduction explains what materialmust already have been covered before each section of the chapter can be covered

impor-ACCESSIBLE TO STUDENTS

It is not enough for a book to present the right topics in the right order It is not evenenough for it be correct and clear to an instructor The material also needs to be pre-sented in a way that is accessible to the novice Like my other textbooks, which proved

to be very popular with students, this book was written to be friendly and accessible tothe student

SUMMARY BOXES

Each major point is summarized in a boxed section These boxed sections are spreadthroughout each chapter They serve as summaries of the material, as a quick referencesource, and as a quick way to learn the C++ syntax for a feature you know about ingeneral but for which you do not know the C++ particulars

SELF-TEST EXERCISES

Each chapter contains numerous test exercises Complete answers for all the test exercises are given at the end of each chapter

Trang 8

self-Preface vii

OTHER FEATURES

Pitfall sections, programming technique sections, and examples of complete programswith sample input and output are given throughout each chapter Each chapter endswith a summary and a collection of programming projects

MYCODEMATE ONLINE TUTORIAL RESOURCE

MyCodeMate is an online resource that provides tutorial help and evaluation of studentwork on programming projects The code displays and selected programming projects

in this edition have been fully integrated into MyCodeMate Using MyCodeMate, astudent can get hints on programming projects, write and compile the project, andreceive feedback on how to address compiler errors messages, and all this can be doneover the Internet from any computer with Internet access Instructors can track eachstudent’s progress and review submitted programming projects A complimentary sub-scription is offered when an access code is bundled with a new copy of this text Sub-scriptions may also be purchased online For more information on MyCodeMate, go to

■ Instructor access to Addison-Wesley’s MyCodeMate

■ Instructors Manual with Solutions

Thanks to Jeff Holcomb at Addison-Wesley who did an excellent job of coordinatingproduction I also want to thank Michelle Brown, Katherine Harutunian, Joyce Wells,and all the other people at Addison-Wesley for their wonderful support A specialthanks to Patty Mahtani at Addison-Wesley for her wonderful support and encourage-ment, and for being Patty

SavitchC++.book Page vii Monday, February 12, 2007 2:38 PM

Trang 9

The following reviewers provided suggestions for this edition I thank them all fortheir hard work and helpful comments

David Cherba, Michigan State UniversityQin Ding, Pennsylvania State University, HarrisburgLawrence S Kroll, San Francisco State UniversityTim H Lin, Cal Poly Pomona

Amar Raheja, Cal Poly PomonaLoren Rhodes, Juniata CollegeVictor Shtern, Boston UniversityAaron Striegel, University of Notre Dame

J Boyd Trolinger, Butte CollegeThe following reviewers provided corrections and suggestions to previous editions

I thank them all for their hard work and helpful commments

Richard Albright, University of Delaware; Jerry K Bilbrey, Jr, Francis Marion University; Albert M K Cheng, University of Houston; Fredrick H Colclough, Colorado Technical University; Drue Coles, Boston University; Stephen Corbesero, Moravian College; Christopher E Cramer; Ron DiNapoli, Cornell University; Martin Dulberg, North Carolina State University H E Dunsmore, Purdue University; Evan Golub, University of Maryland; Stephen P Leach, Florida State University; Alvin S Lim, Auburn University; Tim Lin, California Polytechnical Institute of Pomona; R M Lowe, Clemson University; Kenrick Mock, University

of Alaska, Anchorage; Jeffrey L Popyack, Drexel University; Victoria Rayskin, University of Central Los Angeles; and Joel Weinstein, Northeastern University

A special thanks goes to Kenrick Mock (University of Alaska) who executed theupdating of this edition He had the difficult job of satisfying me, the editor, and him-self I thank him for a truly excellent job

Walter Savitch

Trang 10

Self-Test Exercises and Answers

Strategically placed within each chapter, Self-Test Exercises offer readers an opportunity to assess their mastery of key topics.

Detailed answers are provided at the end

9 Give an output statement that will produce the following message on the screen.

The answer to the question of Life, the Universe, and Everything is 42.

10 Give an input statement that will fill the variable theNumber (of type int ) with a number typed in at the keyboard Precede the input statement with a prompt statement asking the user to enter a whole number.

cout << "Enter two whole numbers: ";

cin >> number1 >> number2;

cout << number1 << " divided by " << number2 << " equals " << (number1/number2) << "\n"

<< "with a remainder of " << (number1%number2) << "\n";

c f = (9.0/5) * c + 32.0;

or

f = 1.8 * c + 32.0;

9 cout << "The answer to the question of\n"

<< "Life, the Universe, and Everything is 42.\n";

10 cout << "Enter a whole number and press Return: ";

return 0;

}

SavitchC++.book Page ix Monday, February 12, 2007 2:38 PM

Trang 11

x Feature Walkthrough

Code Displays

There are abundant code listings

through-out the text Informal comments that

explain potentially confusing or difficult

portions appear alongside the code Key

lines are highlighted and color-coding

visually distinguishes comments (green)

and reserved words (blue).

Tips

These helpful hints instruct readers on best programming practices The author explains the rationale behind these prac- tices and includes suggestions on how to execute them effectively.

Pitfalls

These sections warn of common

mis-takes that can trip up beginning

program-mers and offer advice on how to avoid

them.

Display 5.4 Production Graph Program (part 1 of 4)

1 //Reads data and displays a bar graph showing productivity for each plant.

2 #include <iostream>

3 #include <cmath>

4 using namespace std;

5 const int NUMBER_OF_PLANTS = 4;

6 void inputData( int a[], int lastPlantNumber);

7 //Precondition: lastPlantNumber is the declared size of the array a.

8 //Postcondition: For plantNumber = 1 through lastPlantNumber:

9 //a[plantNumber-1] equals the total production for plant number plantNumber.

(continued)

Look again at the program in Display 5.1 It only works for classes that have exactly gram more versatile is to use a defined constant for the size of each array For example, the program in Display 5.1 could be rewritten to use the following defined constant:

const int NUMBER_OF_STUDENTS = 5;

The line with the array declaration would then be

int i, score[NUMBER_OF_STUDENTS], max;

Of course, all places in the program that have a 5 for the size of the array should also

be changed to have NUMBER_OF_STUDENTS instead of 5 If these changes are made to the program (or better still, if the program had been written this way in the first ply changing the one line that defines the constant NUMBER_OF_STUDENTS

Note that you cannot use a variable for the array size, such as the following:

cout << "Enter number of students:\n";

cin >> number;

int score[number]; //ILLEGAL ON MANY COMPILERS!

Some but not all compilers will allow you to specify an array size with a variable in piler permits it (In Chapter 10 we will discuss a different kind of array whose size can be determined when the program is run.)

TIP: Use a Defined Constant for the Size of an Array

PITF

The use of the terms formal parameter and argument that we follow in this book is argument interchangeably When you see the terms parameter and argument, you

meter for both what we call formal parameters and what we call arguments Other

peo-arguments Do not expect consistency in how people use these two terms (In this

more of an abbreviation than a true inconsistency.)

PITFALL: Arguments in the Wrong Order

PITFALL: Use of the Terms Parameter and Argument

Trang 12

Feature Walkthrough xi

Examples

These sections usually feature a plete program that solves a specific prob- lem The code examples are lengthier than in the standard code displays and highlight useful features of C++.

com-Chapter Summaries

This end-of-chapter tool provides a

cise overview of the fundamental

con-cepts presented in the chapter.

Programming Projects

Found at the end of each chapter, gramming Projects challenge readers to design and implement a C++ program to solve a problem Example solutions for all programming projects are available to instructors.

Pro-142 CHAPTER 4 Parameters and Overloading

EXAMPLE: The swapValues Function

The function swapValues defined in Display 4.2 interchanges the values stored in two variables The description of the function is given by the following function declara- tion and accompanying comment:

void swapValues( int & variable1, in t& variable2);

//Interchanges the values of variable1 and variable2.

To see how the function is supposed to work, assume that the variable firstNum has the value 5 and the variable secondNum has the value 6 and consider the following function call:

vari-To see that this alternative definition cannot work, consider what would happen with this definition and the function call

argu-• A call-by-value formal parameter is a local variable that is initialized to the value

of its corresponding argument when the function is called Occasionally, it is ful to use a formal call-by-value parameter as a local variable.

use-• In the call-by-reference substitution mechanism, the argument should be a able, and the entire variable is substituted for the corresponding argument.

vari-• The way to indicate a call-by-reference parameter in a function definition is to attach the ampersand sign, & , to the type of the formal parameter (A call-by-value parameter is indicated by the absence of an ampersand.)

• An argument corresponding to a call-by-value parameter cannot be changed by a function call An argument corresponding to a call-by-reference parameter can be changed by a function call If you want a function to change the value of a vari- able, then you must use a call-by-reference parameter.

Programming Projects 41 Programming Projects

1 A metric ton is 35,273.92 ounces Write a program that will read the weight of a package of breakfast cereal in ounces and output the weight in metric tons as well as the number of boxes needed to yield one metric ton of cereal.

SavitchC++.book Page xi Monday, February 12, 2007 2:38 PM

Trang 13

xii Feature Walkthrough

MyCodeMate

MyCodeMate brings end-of-chapter

pro-gramming projects to life Working online,

students can view, compile, run, and edit

select programming problems as well as

all code listings from the textbook Best

of all, MyCodeMate’s tutorial feedback

helps students work through common

programming errors, improving their

pro-gramming skills An automated

grade-book allows instructors to assign

MyCodeMate problems and track

stu-dent progress online.

4 Write a program that will read in a length in feet and inches and output the equivalent length in meters and centimeters Use at least three functions: one for input, one or more for calculating, and one for output Include a loop that lets the user repeat this computation for new input values until the user says he or she wants to end the program There are 0.3048 meters in a foot, 100 centime- ters in a meter, and 12 inches in a foot

Trang 14

Chapter 1 C++ BASICS 1

Chapter 2 FLOW OF CONTROL 43

Chapter 3 FUNCTION BASICS 89

Chapter 4 PARAMETERS AND OVERLOADING 133

Chapter 5 ARRAYS 173

Chapter 6 STRUCTURES AND CLASSES 227

Chapter 7 CONSTRUCTORS AND OTHER TOOLS 263

Chapter 8 OPERATOR OVERLOADING, FRIENDS, AND REFERENCES 309

Chapter 9 STRINGS 357

Chapter 10 POINTERS AND DYNAMIC ARRAYS 411

Chapter 11 SEPARATE COMPILATION AND NAMESPACES 465

Chapter 12 STREAMS AND FILE I/O 509

Chapter 13 RECURSION 561

Chapter 14 INHERITANCE 599

Chapter 15 POLYMORPHISM AND VIRTUAL FUNCTIONS 647

Chapter 16 TEMPLATES 675

Chapter 17 LINKED DATA STRUCTURES 713

Chapter 18 EXCEPTION HANDLING 805

Chapter 19 STANDARD TEMPLATE LIBRARY 835

Chapter 20 PATTERNS AND UML 891

Appendix 1 C++ KEYWORDS 911

Appendix 2 PRECEDENCE OF OPERATORS 913

Appendix 3 THE ASCII CHARACTER SET 915

Appendix 4 SOME LIBRARY FUNCTIONS 917

Appendix 5 OLD AND NEW HEADER FILES 925

FURTHER READING 927 INDEX 929

Brief Contents

SavitchC++.book Page xiii Monday, February 12, 2007 7:06 PM

Trang 15

C++ Terminology 4

A Sample C++ Program 4

Identifiers 6 Variables 8 Assignment Statements 10 Pitfall: Uninitialized Variables 12 Tip: Use Meaningful Names 13 More Assignment Statements 13 Assignment Compatibility 14 Literals 15

Escape Sequences 17 Naming Constants 17 Arithmetic Operators and Expressions 19 Integer and Floating-Point Division 21 Pitfall: Uninitialized Variables 22 Type Casting 22

Increment and Decrement Operators 25 Pitfall: Order of Evaluation 27

Output Using cout 28 New Lines in Output 29 Tip: End Each Program with \n or endl 30 Formatting for Numbers with a Decimal Point 31 Output with cerr 32

Input Using cin 32

Tip: Line Breaks in I/O 34

Comments 35

Contents

Trang 16

Contents xv

Libraries and include Directives 36 Namespaces 36

Pitfall: Problems with Library Names 37 Chapter Summary 38

Answers to Self-Test Exercises 39 Programming Projects 41

Building Boolean Expressions 44 Pitfall: Strings of Inequalities 45 Evaluating Boolean Expressions 46 Precedence Rules 48

Pitfall: Integer Values Can Be Used as Boolean Values 52

if-else Statements 54 Compound Statements 56 Pitfall: Using = in Place of == 57

Omitting the else 59

Nested Statements 59 Multiway if-else Statement 59 The switch Statement 60 Pitfall: Forgetting a break in a switch Statement 63 Tip: Use switch Statements for Menus 63

Enumeration Types 64 The Conditional Operator 64

The while and do-while Statements 66 Increment and Decrement Operators Revisited 68 The Comma Operator 70

The for Statement 72 Tip: Repeat-N-Times Loops 74 Pitfall: Extra Semicolon in a for Statement 75 Pitfall: Infinite Loops 75

The break and continue Statements 78 Nested Loops 81

Chapter Summary 81 Answers to Self-Test Exercises 82 Programming Projects 87

SavitchC++.book Page xv Monday, February 12, 2007 7:06 PM

Trang 17

Functions Calling Functions 105 Functions That Return a Boolean Value 108 Defining void Functions 109

return Statements in void Functions 111 Preconditions and Postconditions 111

main Is a Function 113 Recursive Functions 114

Local Variables 115 Procedural Abstraction 118 Global Constants and Global Variables 119 Blocks 122

Nested Scopes 122 Tip: Use Function Calls in Branching and Loop Statements 123 Variables Declared in a for Loop 123

Chapter Summary 124 Answers to Self-Test Exercises 124 Programming Projects 128

Call-by-Value Parameters 134

A First Look at Call-by-Reference Parameters 137 Call-by-Reference Mechanism in Detail 139 Constant Reference Parameters 141 Example: The swapValues Function 142 Tip: Think of Actions, Not Code 143 Mixed Parameter Lists 144

Tip: What Kind of Parameter to Use 145

Trang 18

Contents xvii

Pitfall: Inadvertent Local Variables 147 Tip: Choosing Formal Parameter Names 149 Example: Buying Pizza 149

Introduction to Overloading 152 Pitfall: Automatic Type Conversion and Overloading 155 Rules for Resolving Overloading 156

Example: Revised Pizza-Buying Program 158 Default Arguments 160

The assert Macro 162 Stubs and Drivers 163 Chapter Summary 166 Answers to Self-Test Exercises 167 Programming Projects 168

Declaring and Referencing Arrays 174 Tip: Use for Loops with Arrays 177 Pitfall: Array Indexes Always Start with Zero 177 Tip: Use a Defined Constant for the Size of an Array 177 Arrays in Memory 178

Pitfall: Array Index Out of Range 180 Initializing Arrays 180

Indexed Variables as Function Arguments 183 Entire Arrays as Function Arguments 184 The const Parameter Modifier 188 Pitfall: Inconsistent Use of const Parameters 189 Example: Production Graph 190

Functions That Return an Array 190

Tip: Do Not Skimp on Formal Parameters 196 Partially Filled Arrays 196

Example: Searching an Array 199 Example: Sorting an Array 201

SavitchC++.book Page xvii Monday, February 12, 2007 7:06 PM

Trang 19

xviii Contents

Multidimensional Array Basics 206 Multidimensional Array Parameters 208 Example: Two-Dimensional Grading Program 209 Chapter Summary 214

Answers to Self-Test Exercises 215 Programming Projects 219

Structure Types 230 Pitfall: Forgetting a Semicolon in a Structure Definition 234 Structures as Function Arguments 234

Tip: Use Hierarchical Structures 235 Initializing Structures 238

Structures versus Classes 255 Tip: Thinking Objects 257 Chapter Summary 257 Answers to Self-Test Exercises 258 Programming Projects 260

Constructor Definitions 264 Pitfall: Constructors with No Arguments 269 Tip: Always Include a Default Constructor 271 Explicit Constructor Calls 271

Example: BankAccount Class 274 Class Type Member Variables 281

Trang 20

Vector Basics 297 Pitfall: Using Square Brackets beyond the Vector Size 299 Tip: Vector Assignment Is Well Behaved 301

Efficiency Issues 301 Chapter Summary 303 Answers to Self-Test Exercises 303 Programming Projects 305

Overloading Basics 311 Tip: A Constructor Can Return an Object 316 Returning by const Value 317

Tip: Returning Member Variables of a Class Type 320 Overloading Unary Operators 321

Overloading as Member Functions 322 Tip: A Class Has Access to All Its Objects 324 Overloading Function Application ( ) 325

Pitfall: Overloading && , || , and the Comma Operator 325

Constructors for Automatic Type Conversion 326 Pitfall: Member Operators and Automatic Type Conversion 327 Friend Functions 328

Friend Classes 330 Pitfall: Compilers without Friends 332

References 333 Pitfall: Returning a Reference to Certain Member Variables 335 Overloading >> and << 335

Tip: What Mode of Returned Value to Use 342 The Assignment Operator 344

Overloading the Increment and Decrement Operators 345 Overloading the Array Operator [ ] 348

Overloading Based on L-Value versus R-Value 350

SavitchC++.book Page xix Monday, February 12, 2007 7:06 PM

Trang 21

xx Contents

Chapter Summary 350 Answers to Self-Test Exercises 350 Programming Projects 353

C-String Values and C-String Variables 359 Pitfall: Using = and == with C-strings 363

Other Functions in <cstring> 364

C-String Input and Output 368

Character I/O 371 The Member Functions get and put 372

Example: Checking Input Using a Newline Function 374 Pitfall: Unexpected '\n' in Input 376

Pitfall: (continued) 377 The putback , peek , and ignore Member Functions 377 Character-Manipulating Functions 380

Pitfall: toupper and tolower Return int Values 382

Introduction to the Standard Class string 384

I/O with the Class string 387

Tip: More Versions of getline 390

Pitfall: Mixing cin >> variable; and getline 391

String Processing with the Class string 392

Example: Palindrome Testing 396 Converting between string Objects and C-Strings 400 Chapter Summary 400

Answers to Self-Test Exercises 401 Programming Projects 405

Pointer Variables 413 Basic Memory Management 421 Pitfall: Dangling Pointers 424 Dynamic Variables and Automatic Variables 424 Tip: Define Pointer Types 425

Pitfall: Pointers as Call-by-Value Parameters 427 Uses for Pointers 429

Trang 22

Contents xxi

Array Variables and Pointer Variables 430 Creating and Using Dynamic Arrays 431 Example: A Function That Returns an Array 435 Pointer Arithmetic 437

Multidimensional Dynamic Arrays 438

The -> Operator 441 The this Pointer 442 Overloading the Assignment Operator 443 Example: A Class for Partially Filled Arrays 445 Destructors 454

Copy Constructors 455 Chapter Summary 459 Answers to Self-Test Exercises 460 Programming Projects 462

Encapsulation Reviewed 467 Header Files and Implementation Files 468 Example: DigitalTime Class 476

Tip: Reusable Components 477 Using #ifndef 477

Tip: Defining Other Libraries 480

Namespaces and using Directives 481 Creating a Namespace 483

Using Declarations 486 Qualifying Names 488 Tip: Choosing a Name for a Namespace 490 Example: A Class Definition in a Namespace 490 Unnamed Namespaces 491

Pitfall: Confusing the Global Namespace and the Unnamed Namespace 498 Tip: Unnamed Namespaces Replace the static Qualifier 499

Tip: Hiding Helping Functions 499 Nested Namespaces 500

Tip: What Namespace Specification Should You Use? 500 Chapter Summary 503

Answers to Self-Test Exercises 504 Programming Projects 505

Trang 23

Chapter 12 Streams and File I/O 509

File I/O 511 Pitfall: Restrictions on Stream Variables 516 Appending to a File 516

Tip: Another Syntax for Opening a File 518 Tip: Check That a File Was Opened Successfully 520 Character I/O 522

Checking for the End of a File 523

File Names as Input 527 Formatting Output with Stream Functions 528 Manipulators 532

Saving Flag Settings 533 More Output Stream Member Functions 534 Example: Cleaning Up a File Format 536 Example: Editing a Text File 538

Inheritance among Stream Classes 541 Example: Another newLine Function 543

Chapter Summary 549 Answers to Self-Test Exercises 549 Programming Projects 552

Example: Vertical Numbers 563 Tracing a Recursive Call 566

A Closer Look at Recursion 569 Pitfall: Infinite Recursion 570 Stacks for Recursion 572 Pitfall: Stack Overflow 573 Recursion versus Iteration 574

General Form for a Recursive Function That Returns a Value 575 Example: Another Powers Function 576

Trang 24

Chapter Summary 590 Answers to Self-Test Exercises 591 Programming Projects 595

Derived Classes 600 Constructors in Derived Classes 610 Pitfall: Use of Private Member Variables from the Base Class 612 Pitfall: Private Member Functions Are Effectively Not Inherited 614 The protected Qualifier 614

Redefinition of Member Functions 617 Redefining versus Overloading 618 Access to a Redefined Base Function 620 Functions That Are Not Inherited 621

Assignment Operators and Copy Constructors in Derived Classes 622 Destructors in Derived Classes 623

Example: Partially Filled Array with Backup 624 Pitfall: Same Object on Both Sides of the Assignment Operator 633 Example: Alternate Implementation of PFArrayDBak 633

Tip: A Class Has Access to Private Members of All Objects of the Class 636 Tip: “Is a” versus “Has a” 636

Protected and Private Inheritance 637 Multiple Inheritance 638

Chapter Summary 639 Answers to Self-Test Exercises 639 Programming Projects 641

Late Binding 648 Virtual Functions in C++ 649 Tip: The Virtual Property Is Inherited 656

Trang 25

Tip: When to Use a Virtual Function 656 Pitfall: Omitting the Definition of a Virtual Member Function 657 Abstract Classes and Pure Virtual Functions 657

Example: An Abstract Class 659

Virtual Functions and Extended Type Compatibility 661 Pitfall: The Slicing Problem 665

Tip: Make Destructors Virtual 666 Downcasting and Upcasting 667 How C++ Implements Virtual Functions 668 Chapter Summary 670

Answers to Self-Test Exercises 671 Programming Projects 672

Syntax for Function Templates 678 Pitfall: Compiler Complications 681 Tip: How to Define Templates 682 Example: A Generic Sorting Function 683 Pitfall: Using a Template with an Inappropriate Type 688

Syntax for Class Templates 691 Example: An Array Template Class 695 The vector and basic_string Templates 701

Example: Template Class for a Partially Filled Array with Backup 702 Chapter Summary 708

Answers to Self-Test Exercises 708 Programming Projects 711

Nodes 715 Linked Lists 720 Inserting a Node at the Head of a List 722 Pitfall: Losing Nodes 725

Trang 26

Contents xxv

Inserting and Removing Nodes Inside a List 725 Pitfall: Using the Assignment Operator with Dynamic Data Structures 729 Searching a Linked List 730

Doubly Linked Lists 732 Adding a Node to a Doubly Linked List 734 Deleting a Node from a Doubly Linked List 736 Example: A Generic Sorting Template Version of Linked List Tools 741

Example: A Stack Template Class 745 Example: A Queue Template Class 752 Tip: A Comment on Namespaces 755 Friend Classes and Similar Alternatives 756 Example: Hash Tables with Chaining 759 Efficiency of Hash Tables 765

Example: A Set Template Class 766 Efficiency of Sets Using Linked Lists 772

Pointers as Iterators 774 Iterator Classes 774 Example: An Iterator Class 776

Tree Properties 783 Example: A Tree Template Class 785 Chapter Summary 790

Answers to Self-Test Exercises 791 Programming Projects 800

A Toy Example of Exception Handling 807 Defining Your Own Exception Classes 816 Multiple Throws and Catches 816

Pitfall: Catch the More Specific Exception First 820 Tip: Exception Classes Can Be Trivial 821

Throwing an Exception in a Function 821 Exception Specification 823

Pitfall: Exception Specification in Derived Classes 825

Trang 27

18.2 PROGRAMMING TECHNIQUES FOR EXCEPTION HANDLING 826

When to Throw an Exception 827 Pitfall: Uncaught Exceptions 828 Pitfall: Nested try-catch Blocks 829 Pitfall: Overuse of Exceptions 829 Exception Class Hierarchies 830 Testing for Available Memory 830 Rethrowing an Exception 831 Chapter Summary 831 Answers to Self-Test Exercises 831 Programming Projects 833

Iterator Basics 837 Pitfall: Compiler Problems 842 Kinds of Iterators 843

Constant and Mutable Iterators 846 Reverse Iterators 848

Other Kinds of Iterators 849

Sequential Containers 850 Pitfall: Iterators and Removing Elements 856 Tip: Type Definitions in Containers 856 The Container Adapters stack and queue 856

Pitfall: Underlying Containers 857 The Associative Containers set and map 860

Efficiency 865

Running Times and Big-O Notation 868 Container Access Running Times 872 Nonmodifying Sequence Algorithms 873 Modifying Sequence Algorithms 878 Set Algorithms 879

Sorting Algorithms 881 Chapter Summary 881 Answers to Self-Test Exercises 882 Programming Projects 884

Trang 28

Contents xxvii

Adapter Pattern 893 The Model-View-Controller Pattern 893 Example: A Sorting Pattern 895

Efficiency of the Sorting Pattern 901 Tip: Pragmatics and Patterns 902 Pattern Formalism 903

History of UML 904 UML Class Diagrams 904 Class Interactions 905 Chapter Summary 905 Answers to Self-Test Exercises 906 Programming Projects 907

Appendix 1 C++ Keywords 911

Appendix 2 Precedence of Operators 913

Appendix 3 The ASCII Character Set 915

Appendix 4 Some Library Functions 917

Appendix 5 Old and New Header Files 925

Further Reading 927 Index 929

Trang 30

1 C++ Basics

Increment and Decrement Operators 25 Pitfall: Order of Evaluation 27

Tip: End Each Program with \n or endl 30 Formatting for Numbers with a Decimal Point 31

Tip: Line Breaks in I/O 34

Libraries and include Directives 36

Trang 31

1 C++ Basics

The Analytical Engine has no pretensions whatever to originate anything It can do whatever we know how to order it to perform It can follow analysis; but it has no power of anticipating any analytical relations or truths Its province is to assist us in making available what

we are already acquainted with.

ADA AUGUSTA, Countess of Lovelace

Introduction

This chapter introduces the C++ language and gives enough detail to allow you tohandle simple programs involving expressions, assignments, and console input/output(I/O) The details of assignments and expressions are similar to those of most otherhigh-level languages Every language has its own console I/O syntax, so if you are notfamiliar with C++, that may look new and different to you

Language is the only instrument of science.

SAMUEL JOHNSON

This section gives an overview of the C++ programming language

Origins of the C++ Language

The C++ programming language can be thought of as the C programming languagewith classes (and other modern features added) The C programming language wasdeveloped by Dennis Ritchie of AT&T Bell Laboratories in the 1970s It was first usedfor writing and maintaining the UNIX operating system (Up until that time, UNIXsystems programs were written either in assembly language or in a language called B, alanguage developed by Ken Thompson, the originator of UNIX.) C is a general-pur-pose language that can be used for writing any sort of program, but its success and pop-ularity are closely tied to the UNIX operating system If you wanted to maintain yourUNIX system, you needed to use C C and UNIX fit together so well that soon not justsystems programs but almost all commercial programs that ran under UNIX were writ-ten in the C language C became so popular that versions of the language were writtenfor other popular operating systems; its use is thus not limited to computers that useUNIX However, despite its popularity, C was not without its shortcomings

Trang 32

Introduction to C++ 3

The C language is peculiar because it is a high-level language with many of the tures of a low-level language C is somewhere in between the two extremes of a veryhigh-level language and a low-level language, and therein lies both its strengths and itsweaknesses Like (low-level) assembly language, C language programs can directlymanipulate the computer’s memory On the other hand, C has the features of a high-level language, which makes it easier to read and write than assembly language Thismakes C an excellent choice for writing systems programs, but for other programs(and in some sense even for systems programs) C is not as easy to understand as otherlanguages; also, it does not have as many automatic checks as some other high-levellanguages

fea-To overcome these and other shortcomings of C, Bjarne Stroustrup of AT&T BellLaboratories developed C++ in the early 1980s Stroustrup designed C++ to be a bet-ter C Most of C is a subset of C++, and so most C programs are also C++ programs

(The reverse is not true; many C++ programs are definitely not C programs.) Unlike

C, C++ has facilities for classes and so can be used for object-oriented programming

C++ and Object-Oriented Programming

Object-oriented programming (OOP) is a currently popular and powerful ming technique The main characteristics of OOP are encapsulation, inheritance, andpolymorphism Encapsulation is a form of information hiding or abstraction Inherit-ance has to do with writing reusable code Polymorphism refers to a way that a singlename can have multiple meanings in the context of inheritance Having made thosestatements, we must admit that they will hold little meaning for readers who have notheard of OOP before However, we will describe all these terms in detail later in thisbook C++ accommodates OOP by providing classes, a kind of data type combiningboth data and algorithms C++ is not what some authorities would call a “pure OOPlanguage.” C++ tempers its OOP features with concerns for efficiency and what somemight call “practicality.” This combination has made C++ currently the most widelyused OOP language, although not all of its usage strictly follows the OOP philosophy

program-The Character of C++

C++ has classes that allow it to be used as an object-oriented language It allows foroverloading of functions and operators (All these terms will be explained eventually,

so do not be concerned if you do not fully understand some terms.) C++’s connection

to the C language gives it a more traditional look than newer object-oriented guages, yet it has more powerful abstraction mechanisms than many other currentlypopular languages C++ has a template facility that allows for full and direct imple-mentation of algorithm abstraction C++ templates allow you to code using parame-ters for types The newest C++ standard, and most C++ compilers, allow multiplenamespaces to accommodate more reuse of class and function names The excep-tion handling facilities in C++ are similar to what you would find in other program-ming languages Memory management in C++ is similar to that in C The

lan-SavitchC++.book Page 3 Monday, February 12, 2007 1:49 PM

Trang 33

4 CHAPTER 1 C++ Basics

programmer must allocate his or her own memory and handle his or her own garbagecollection Most compilers will allow you to do C-style memory management in C++,since C is essentially a subset of C++ However, C++ also has its own syntax for a C++style of memory management, and you are advised to use the C++ style of memorymanagement when coding in C++ This book uses only the C++ style of memorymanagement

C++ Terminology

All procedure-like entities are called functions in C++ Things that are called

C++ As we will see in the next subsection, a C++ program is basically just a functioncalled main; when you run a program, the run-time system automatically invokes thefunction named main Other C++ terminology is pretty much the same as most otherprogramming languages, and in any case, will be explained when each concept isintroduced

A Sample C++ Program

Display 1.1 contains a simple C++ program and two possible screen displays thatmight be generated when a user runs the program A C++ program is really a functiondefinition for a function named main When the program is run, the function namedmain is invoked The body of the function main is enclosed in braces, {} When theprogram is run, the statements in the braces are executed

The following two lines set up things so that the libraries with console input andoutput facilities are available to the program The details concerning these two linesand related topics are covered in Section 1.3 and in Chapters 9, 11, and 12

a function that does not return a value However, the above form is the most sally accepted way to start the main function of a C++ program

univer-The program ends when the following statement is executed:

return 0;

This statement ends the invocation of the function main and returns 0 as the function’svalue According to the ANSI/ISO C++ standard, this statement is not required, butmany compilers still require it Chapter 3 covers all these details about C++ functions

functions

program

int main()

return 0;

Trang 34

Introduction to C++ 5

Variable declarations in C++ are similar to what they are in other programming guages The following line from Display 1.1 declares the variable numberOfLanguages:int numberOfLanguages;

lan-The type int is one of the C++ types for whole numbers (integers)

If you have not programmed in C++ before, then the use of cin and cout for sole I/O is likely to be new to you That topic is covered a little later in this chapter,

con-User types in 0 on the keyboard.

User types in 1 on the keyboard.

Display 1.1 A Sample C++ Program

11 cout << "Read the preface You may prefer\n"

12 << "a more elementary book by the same author.\n";

How many programming languages have you used? 0

Read the preface You may prefer

a more elementary book by the same author.

Sample Dialogue 2

Hello reader.

Welcome to C++.

How many programming languages have you used? 1

Enjoy the book

SavitchC++.book Page 5 Monday, February 12, 2007 1:49 PM

Trang 35

The linescout << "Read the preface You may prefer\n"

<< "a more elementary book by the same author.\n";

output two strings instead of just one string The details are explained in Section 1.3 later

in this chapter, but this brief introduction will be enough to allow you to understand thesimple use of cin and cout in the examples that precede Section 1.3 The symbolism \n isthe newline character, which instructs the computer to start a new line of output

Although you may not yet be certain of the exact details of how to write such ments, you can probably guess the meaning of the if-else statement The details will

state-be explained in the next chapter

(By the way, if you have not had at least some experience with some programminglanguages, you should read the preface to see if you might not prefer the more elemen-tary book discussed in this program You need not have had any experience with C++

to read this book, but some minimal programming experience is strongly suggested.)

Statements

Once a person has understood the way variables are used in programming, he has understood the quintessence of programming.

Variables, expressions, and assignments in C++ are similar to those in most othergeneral-purpose languages

Identifiers

The name of a variable (or other item you might define in a program) is called an

and all the rest of the characters must be letters, digits, or the underscore symbol Forexample, the following are all valid identifiers:

x x1 x_1 _abc ABC123z7 sum RATE count data2 bigBonus

identifier

Trang 36

Variables, Expressions, and Assignment Statements 7

All the above names are legal and would be accepted by the compiler, but the first fiveare poor choices for identifiers because they are not descriptive of the identifier’s use

None of the following are legal identifiers, and all would be rejected by the compiler:

12 3X %change data-1 myfirst.c PROG.CPPThe first three are not allowed because they do not start with a letter or an underscore

The remaining three are not identifiers because they contain symbols other than ters, digits, and the underscore symbol

let-Although it is legal to start an identifier with an underscore, you should avoiddoing so, because identifiers starting with an underscore are informally reserved forsystem identifiers and standard libraries

C++ is a case-sensitive language; that is, it distinguishes between uppercase andlowercase letters in the spelling of identifiers Hence, the following are three distinctidentifiers and could be used to name three distinct variables:

rate RATE RateHowever, it is not a good idea to use two such variants in the same program, since thatmight be confusing Although it is not required by C++, variables are usually spelledwith their first letter in lowercase The predefined identifiers, such as main, cin, cout,and so forth, must be spelled in all lowercase letters The convention that is nowbecoming universal in object-oriented programming is to spell variable names with amix of upper- and lowercase letters (and digits), to always start a variable name with alowercase letter, and to indicate “word” boundaries with an uppercase letter, as illus-trated by the following variable names:

topSpeed, bankRate1, bankRate2, timeOfArrivalThis convention is not as common in C++ as in some other object-oriented languages,but is becoming more widely used and is a good convention to follow

A C++ identifier can be of any length, although some compilers will ignore allcharacters after some (large) specified number of initial characters

There is a special class of identifiers, called keywords or reserved words, that have

a predefined meaning in C++ and cannot be used as names for variables or anythingelse In the code displays of this book keywords are shown in a different color A com-plete list of keywords is given in Appendix 1

Identifiers

A C++ identifier must start with either a letter or the underscore symbol, and the ing characters must all be letters, digits, or the underscore symbol C++ identifiers are case sensitive and have no limit to their length.

Trang 37

Some predefined words, such as cin and cout, are not keywords These predefinedwords are not part of the core C++ language, and you are allowed to redefine them.Although these predefined words are not keywords, they are defined in librariesrequired by the C++ language standard Needless to say, using a predefined identifierfor anything other than its standard meaning can be confusing and dangerous andthus should be avoided The safest and easiest practice is to treat all predefined identi-fiers as if they were keywords

Variables

Every variable in a C++ program must be declared before it is used When you declare

a variable you are telling the compiler—and, ultimately, the computer—what kind ofdata you will be storing in the variable For example, the following are two definitionsthat might occur in a C++ program:

int numberOfBeans;

double oneWeight, totalWeight;

The first defines the variable numberOfBeans so that it can hold a value of type int,that is, a whole number The name int is an abbreviation for “integer.” The type int isone of the types for whole numbers The second definition declares oneWeight andtotalWeight to be variables of type double, which is one of the types for numbers

with a decimal point (known as floating-point numbers) As illustrated here, when

there is more than one variable in a definition, the variables are separated by commas.Also, note that each definition ends with a semicolon

Every variable must be declared before it is used; otherwise, variables may bedeclared any place Of course, they should always be declared in a location that makesthe program easier to read Typically, variables are declared either just before they areused or at the start of a block (indicated by an opening brace, { ) Any legal identifier,other than a reserved word, may be used for a variable name.1

C++ has basic types for characters, integers, and floating-point numbers (numberswith a decimal point) Display 1.2 lists the basic C++ types The commonly used typefor integers is int The type char is the type for single characters The type char can betreated as an integer type, but we do not encourage you to do so The commonly usedtype for floating-point numbers is double, and so you should use double for floating-point numbers unless you have a specific reason to use one of the other floating-point

1 C++ makes a distinction between declaring and defining an identifier When an identifier is declared,

the name is introduced When it is defined, storage for the named item is allocated For the kind of

variables we discuss in this chapter, and for much more of the book, what we are calling a variable

declaration both declares the variable and defines the variable, that is, allocates storage for the

vari-able Many authors blur the distinction between variable definition and variable declaration The ference between declaring and defining an identifier is more important for other kinds of identifiers, which we will encounter in later chapters.

dif-declare

floating-point

number

Trang 38

Variables, Expressions, and Assignment Statements 9

types The type bool (short for Boolean) has the values true and false It is not aninteger type, but to accommodate older code, you can convert back and forth betweenbool and any of the integer types In addition, the standard library named string pro-vides the type string, which is used for strings of characters The programmer candefine types for arrays, classes, and pointers, all of which are discussed in later chapters

of this book

Display 1.2 Simple Types

short (also called short int)

2 bytes -32,767 to 32,767 Not applicable

2,147,483,647

Not applicable

long (also called long int)

as an integer type, although we

do not mend doing so.)

recom-Not applicable

The values listed here are only sample values to give you a general idea of how the

types differ The values for any of these entries may be different on your system

Preci-sion refers to the number of meaningful digits, including digits in front of the decimal

point The ranges for the types float, double, and long double are the ranges for positive numbers Negative numbers have a similar range, but with a negative sign in front of each number.

Trang 39

Each of the integer types has an unsigned version that includes only nonnegative

values These types are unsigned short, unsigned int, and unsigned long Theirranges do not exactly correspond to the ranges of the positive values of the typesshort, int, and long, but are likely to be larger (since they use the same storage astheir corresponding types short, int, or long, but need not remember a sign) You areunlikely to need these types, but may run into them in specifications for predefinedfunctions in some of the C++ libraries, which we discuss in Chapter 3

or a more complicated expression made up of variables, numbers, operators, and tion invocations An assignment statement instructs the computer to evaluate (that is,

func-to compute the value of ) the expression on the right-hand side of the equal sign and func-to

In an assignment statement, first the expression on the right-hand side of the equal sign

is evaluated and then the variable on the left-hand side of the equal sign is set equal to this value.

Trang 40

Variables, Expressions, and Assignment Statements 11

set the value of the variable on the left-hand side equal to the value of that expression

The following are examples of C++ assignment statements:

totalWeight = oneWeight * numberOfBeans;

temperature = 98.6;

count = count + 2;

The first assignment statement sets the value of totalWeight equal to the number inthe variable oneWeight multiplied by the number in numberOfBeans (Multiplication isexpressed using the asterisk, *, in C++.) The second assignment statement sets thevalue of temperature to 98.6 The third assignment statement increases the value ofthe variable count by 2

In C++, assignment statements can be used as expressions When used as an sion, an assignment statement returns the value assigned to the variable For example,consider

expres-n = (m = 2);

The subexpression (m = 2) both changes the value of m to 2 and returns the value 2.Thus, this sets both n and m equal to 2 As you will see when we discuss precedence ofoperators in detail in Chapter 2, you can omit the parentheses, so the assignmentstatement under discussion can be written as

n = m = 2;

We advise you not to use an assignment statement as an expression, but you should

be aware of this behavior because it will help you understand certain kinds of codingerrors For one thing, it will explain why you will not get an error message when youmistakenly write

n = m = 2;

when you meant to write

n = m + 2;

(This is an easy mistake to make since = and + are on the same keyboard key.)

Lvalues and Rvalues

Authors often refer to lvalue and rvalue in C++ books An lvalue is anything that can

appear on the left-hand side of an assignment operator (=), which means any kind of

vari-able An rvalue is anything that can appear on the right-hand side of an assignment

oper-ator, which means any expression that evaluates to a value.

Ngày đăng: 19/03/2014, 14:14

TỪ KHÓA LIÊN QUAN