logo资料库

c++ for everyone 2nd edition.pdf

第1页 / 共562页
第2页 / 共562页
第3页 / 共562页
第4页 / 共562页
第5页 / 共562页
第6页 / 共562页
第7页 / 共562页
第8页 / 共562页
资料共562页,剩余部分请下载后查看
COVER
TITLE PAGE
COPYRIGHT
PREFACE
A WALKTHOUGH OF THE LEARNING AIDS
ACKNOWLEDGMENTS
CONTENTS
SPECIAL FEATURES
CHAPTER 1 INTRODUCTION
1.1 What is Programming
1.2 The Anatomy of a Computer
1.3 Machine Code and Programming Languages
1.4 Becoming Familiar with Your Programming Environment
1.5 Analyzing Your First Program
1.6 Errors
1.7 Problem Solving: Algorithm Design
CHAPTER SUMMARY
REVIEW EXERCISES
PROGRAMMING EXERCISES
ANSWERS TO SELF - CHECK QUESTIONS
CHAPTER 2 FUNDAMENTAL DATA TYPES
2.1 Variables
2.1.1 Variable Definitions
2.1.2 Number Types
2.1.3 Variable Names
2.1.4 The Assignment Statement
2.1.5 Constants
2.1.6 Comments
2.2 Arithmetic
2.2.1 Arithmetic Operators
2.2.2 Increment and Decrement
2.2.3 Integer Division and Remainder
2.2.4 Converting Floating-Point Numbers to Integers
2.2.5 Powers and Roots
2.3 Input and Output
2.3.1 Input
2.3.2 Formatted Output
2.4 Problem Solving: First Do It By Hand
2.5 Strings
2.5.1 The String Type
2.5.2 Concatenation
2.5.3 String Input
2.5.4 String Functions
CHAPTER SUMMARY
REVIEW EXERCISES
PROGRAMMING EXERCISES
ANSWERS TO SELF - CHECK QUESTIONS
CHAPTER 3 DECISIONS
3.1 The if Statement
3.2 Comparing Numbers and Strings
3.3 Multiple Alternatives
3.4 Nested Branches
3.5 Problem Solving: Flowcharts
3.6 Problem Solving: Test Cases
3.7 Boolean Variables and Operators
3.8 Application: Input Validation
CHAPTER SUMMARY
REVIEW EXERCISES
PROGRAMMING EXERCISES
ANSWERS TO SELF - CHECK QUESTIONS
CHAPTER 4 LOOPS
4.1 The while Loop
4.2 Problem Solving: Hand-Tracing
4.3 The for Loop
4.4 The do Loop
4.5 Processing Input
4.6 Problem Solving: Storyboards
4.7 Common Loop Algorithms
4.7.1 Sum and Average Value
4.7.2 Counting Matches
4.7.3 Finding the First Match
4.7.4 Maximum and Minimum
4.7.5 Comparing Adjacent Values
4.8 Nested Loops
4.9 Random Numbers and Simulations
4.9.1 Generating Random Numbers
4.9.2 Simulating Die Tosses
4.9.3 The Monte Carlo Method
CHAPTER SUMMARY
REVIEW EXERCISES
PROGRAMMING EXERCISES
ANSWERS TO SELF - CHECK QUESTIONS
CHAPTER 5 FUNCTIONS
5.1 Functions as Black Boxes
5.2 Implementing Functions
5.3 Parameter Passing
5.4 Return Values
5.5 Functions Without Return Values
5.6 Problem Solving: Reusable Functions
5.7 Problem Solving: Stepwise Refinement
5.8 Variable Scope and Global Variables
5.9 Reference Parameters
5.10 Recursive Functions (Optional)
CHAPTER SUMMARY
REVIEW EXERCISES
PROGRAMMING EXERCISES
ANSWERS TO SELF - CHECK QUESTIONS
CHAPTER 6 ARRAYS AND VECTORS
6.1 Arrays
6.1.1 Defining Arrays
6.1.2 Accessing Array Elements
6.1.3 Partially Filled Arrays
6.2 Common Array Algorithms
6.2.1 Filling
6.2.2 Copying
6.2.3 Sum and Average Value
6.2.4 Maximum and Minimum
6.2.5 Element Separators
6.2.6 linear Search
6.2.7 Removing an Element
6.2.8 Inserting an Element
6.2.9 Swapping Elements
6.2.10 Reading Input
6.3 Arrays And Functions
6.4 Problem Solving: Adapting Algorithms
6.5 Problem Solving: Discovering Algorithms by Manipulating Physical Objects
6.6 Two-Dimensional Arrays
6.6.1 Defining Two-Dimensional Arrays
6.6.2 Accessing Elements
6.6.3 Computing Row and Column Totals
6.6.4 Two-Dimensional Array Parameters
6.7 Vectors
6.7.1 Defining Vectors
6.7.2 Growing and Shrinking Vectors
6.7.3 Vectors and Functions
6.7.4 Vector Algorithms
CHAPTER SUMMARY
REVIEW EXERCISES
PROGRAMMING EXERCISES
ANSWERS TO SELF - CHECK QUESTIONS
CHAPTER 7 POINTERS
7.1 Defining and Using Pointers
7.1.1 Defining Pointers
7.1.2 Accessing Variables Through Pointers
7.1.3 Initializing Pointers
7.2 Arrays and Pointers
7.2.1 Arrays as Pointers
7.2.2 Pointer Arithmetic
7.2.3 Array Parameter Variables are Pointers
7.3 C and C++ Strings
7.3.1 The Char Type
7.3.2 C Strings
7.3.3 Character Arrays
7.3.4 Converting Between C and C++ Strings
7.3.5 C++ Strings and The [] Operator
7.4 Dynamic Memory Allocation
7.5 Arrays and Vectors of Pointers
7.6 Problem Solving: Draw a Picture
7.7 Structures and Pointers (Optional)
7.7.1 Structures
7.7.2 Pointers to Structures
7.7.3 Structures with Pointer Members
CHAPTER SUMMARY
REVIEW EXERCISES
PROGRAMMING EXERCISES
ANSWERS TO SELF - CHECK QUESTIONS
CHAPTER 8 STREAMS
8.1 Reading and Writing Text Files
8.1.1 Opening a Stream
8.1.2 Reading from a File
8.1.3 Writing to a File
8.1.4 A File Processing Example
8.2 Reading Text Input
8.2.1 Reading Words
8.2.2 Reading Characters
8.2.3 Reading lines
8.3 Writing Text Output
8.4 String Streams
8.5 Command Line Arguments
8.6 Random Access and Binary Files
8.6.1 Random Access
8.6.2 Binary Files
8.6.3 Processing Image Files
CHAPTER SUMMARY
REVIEW EXERCISES
PROGRAMMING EXERCISES
ANSWERS TO SELF - CHECK QUESTIONS
CHAPTER 9 CLASSES
9.1 Object-Oriented Programming
9.2 Specifying the Public Interface of a Class
9.3 Data Members
9.4 Member Functions
9.4.1 Implementing Member Functions
9.4.2 Implicit and Explicit Parameters
9.4.3 Calling a Member Function from a Member Function
9.5 Constructors
9.6 Problem Solving: Tracing Objects
9.7 Problem Solving: Discovering Classes
9.8 Separate Compilation
9.9 Pointers to Objects
9.9.1 Dynamically allocating objects
9.9.2 The -> Operator
9.9.3 The This Pointer
CHAPTER SUMMARY
REVIEW EXERCISES
PROGRAMMING EXERCISES
ANSWERS TO SELF - CHECK QUESTIONS
CHAPTER 10 INHERITANCE
10.1 Inheritance Hierarchies
10.2 Implementing Derived Classes
10.3 Overriding Member Functions
10.4 Virtual Functions and Polymorphism
10.4.1 The Slicing Problem
10.4.2 Pointers to Base and Derived Classes
10.4.3 Virtual Functions
10.4.4 Polymorphism
CHAPTER SUMMARY
REVIEW EXERCISES
PROGRAMMING EXERCISES
ANSWERS TO SELF - CHECK QUESTIONS
APPENDICES
APPENDIX A: C++ LANGUAGE CODING GUIDELINES
APPENDIX B: RESERVED WORD SUMMARY
APPENDIX C: OPERATOR SUMMARY
APPENDIX D: CHARACTER CODES
APPENDIX E: C++ LIBRARY SUMMARY
GLOSSARY
INDEX
CREDITS
This page intentionally left blank
C++ FOR EVERYONE
This page intentionally left blank
C++ FOR EVERYONE S E C O N D E D I T I O N Cay Horstmann San Jose State University John Wiley & Sons, Inc.
VICE PRESIDENT AND EXECUTIVE PUBLISHER EXECUTIVE EDITOR EDITORIAL PROGRAM ASSISTANT PRODUCTION SERVICES MANAGER SENIOR PRODUCTION EDITOR EXECUTIVE MARKETING MANAGER MARKETING ASSISTANT CREATIVE DIRECTOR SENIOR PHOTO EDITOR SENIOR DESIGNER EXECUTIVE MEDIA EDITOR PRODUCTION SERVICES COVER PHOTO Don Fowley Beth Lang Golub Michael Berlin Dorothy Sinclair Janet Foxman Christopher Ruel Diana Smith Harry Nolan Lisa Gee Madelyn Lesure Tom Kulesa Cindy Johnson © Ricardo Azoury/iStockphoto This book was set in Stempel Garamond by Publishing Services, and printed and bound by RRD Jefferson City. The cover was printed by RRD Jefferson City. This book is printed on acid-free paper. Founded in 1807, John Wiley & Sons, Inc. has been a valued source of knowledge and understanding for more than 200 years, helping people around the world meet their needs and fulfill their aspirations. Our company is built on a foundation of principles that include responsibility to the communities we serve and where we live and work. In 2008, we launched a Corporate Citizenship Initiative, a global effort to address the environmental, social, economic, and ethical challenges we face in our business. Among the issues we are addressing are carbon impact, paper specifications and procurement, ethical conduct within our business and among our vendors, and community and charitable support. For more information, please visit our website: www.wiley.com/go/ citizenship. Copyright 2012, 2009 John Wiley & Sons, Inc. All rights reserved. No part of this publication may be re- produced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, pho- tocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Dan- vers, MA 01923, website www.copyright.com. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, (201) 748- 6011, fax (201) 748-6008, website www.wiley.com/go/permissions. Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in their courses during the next academic year. These copies are licensed and may not be sold or transferred to a third party. Upon completion of the review period, please return the evaluation copy to Wiley. Return instruc- tions and a free of charge return shipping label are available at www.wiley.com/go/returnlabel. Outside of the United States, please contact your local representative. Library of Congress Cataloging in Publication Data: Horstmann, Cay S., 1959- C++ for everyone / Cay S. Horstmann. -- 2nd ed. p. cm. Includes index. ISBN 978-0-470-92713-7 (pbk.) 1. C++ (Computer program language) I. Title. QA76.73.C153H6685 2010 005.13'3--dc22 2010039907 ISBN 978-0-470-92713-7 (Main Book) ISBN 978-0-470-92092-3 (Binder-Ready Version) Printed in the United States of America 10 9 8 7 6 5 4 3 2 1
PREFACE This book is an introduction to C++ and computer programming that focuses on the essentials—and on effective learning. The book is designed to serve a wide range of student interests and abilities and is suitable for a first course in programming for computer scientists, engineers, and students in other disciplines. No prior program- ming experience is required, and only a modest amount of high school algebra is needed. Here are the key features of this book: Guidance and worked examples help students succeed. Beginning programmers often ask “How do I start? Now what do I do?” Of course, an activity as complex as programming cannot be reduced to cookbook-style instruc- tions. However, step-by-step guidance is immensely helpful for building confidence and providing an outline for the task at hand. “Problem Solving” sections stress the importance of design and planning. “How To” guides help students with common programming tasks. Additional Worked Examples are available online. Practice makes perfect. Of course, programming students need to be able to implement nontrivial programs, but they first need to have the confidence that they can succeed. This book contains a substantial number of self-check questions at the end of each section. “Practice It” pointers suggest exercises to try after each section. At the end of each chapter, you will find a great variety of programming assignments, ranging from simple practice problems to realistic applications. Teach computer science principles, not just C++ or object-orientation. This book uses the C++ programming language as a vehicle for introducing com- puter sci ence concepts. A substantial subset of the C++ language is covered, focusing on the modern features of standard C++ that make students productive. The book takes a traditional route, stressing control structures, procedural decomposition, and array algorithms, before turning to the design of classes in the final chapters. A visual approach motivates the reader and eases navigation. Photographs present visual analogies that explain the nature and behavior of computer concepts. Step-by- step figures illustrate complex program operations. Syntax boxes and example tables present a variety of typical and special cases in a compact format. It is easy to get the “lay of the land” by browsing the visuals, before focusing on the textual material. Focus on the essentials while being technically accurate. An encyclopedic coverage is not helpful for a begin- ning programmer, but neither is the opposite— reducing the material to a list of simplistic bullet points. In this book, the essentials are presented in digestible chunks, with separate notes that go deeper into good prac- tices or language features when the reader is ready for the additional information. You will not find artificial over-simplifications that give an illusion of knowledge. Visual features help the reader with navigation. v
vi Preface New to This Edition Problem Solving Strategies This edition adds practical, step-by-step illustrations of techniques that can help stu- dents devise and evaluate solutions to programming problems. Introduced where they are most relevant, these strategies address barriers to success for many students. Strategies included are: • Algorithm Design (with pseudocode) • First Do It By Hand (doing sample • Stepwise Refinement • Adapting Algorithms • Discover Algorithms by Manipulat- calculations by hand) • Flowcharts • Test Cases • Hand-Tracing • Storyboards • Reusable Functions ing Physical Objects • Draw a Picture (pointer diagrams) • Tracing Objects (identifying state and behavior) • Discovering Classes Optional Engineering Exercises End-of-chapter exercises have been enhanced with problems from scientific and engineering domains. Geared to students learning C++ for a technical major, the exercises are designed to illustrate the value of programming in those fields. Addi- tional exercises are available on the book’s companion web site. New and Reorganized Topics All chapters were revised and enhanced to respond to user feedback and improve the flow of topics. Loop algorithms are now introduced explicitly in Chapter 4. Debug- ging is now introduced in a lengthy Worked Example in Chapter 5. Arrays are cov- ered before vectors are introduced in Chapter 6, and a new section on vector algo- rithms builds on the array algorithms presented earlier in the chapter. A new optional section on structure types is now in Chapter 7. New example tables, photos, and exercises appear throughout the book. A Tour of the Book The core material of the book is: Chapter 1. Introduction Chapter 2. Fundamental Data Types Chapter 3. Decisions Chapter 4. Loops Chapter 5. Functions Chapter 6. Arrays and Vectors In a course for engineers with a need for systems and embedded programming, you will want to cover Chapter 7 on pointers. Sections 7.1 and 7.4 are sufficient for using pointers with polymorphism in Chapter 10.
分享到:
收藏