C++ how to program 10th global edition

1.1K 935 0
C++ how to program 10th global edition

Đ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

This page intentionally left blank Paul Deitel Deitel & Associates, Inc Harvey Deitel Deitel & Associates, Inc Vice President, Editorial Director: Marcia Horton Acquisitions Editor: Tracy Johnson Editorial Assistant: Kristy Alaura Acquisitions Editor, Global Editions: Sourabh Maheshwari VP of Marketing: Christy Lesko Director of Field Marketing: Tim Galligan Product Marketing Manager: Bram Van Kempen Field Marketing Manager: Demetrius Hall Marketing Assistant: Jon Bryant Director of Product Management: Erin Gregg Team Lead, Program and Project Management: Scott Disanno Program Manager: Carole Snyder Project Manager: Robert Engelhardt Project Editor, Global Editions: K.K Neelakantan Senior Manufacturing Controller, Global Editions: Trudy Kimber Senior Specialist, Program Planning and Support: Maura Zaldivar-Garcia Media Production Manager, Global Editions: Vikram Kumar Cover Art: Finevector / Shutterstock Cover Design: Lumina Datamatics R&P Manager: Rachel Youdelman R&P Project Manager: Timothy Nicholls Inventory Manager: Meredith Maresca Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on page Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world Visit us on the World Wide Web at: www.pearsonglobaleditions.com © Pearson Education Limited 2017 The rights of Paul Deitel and Harvey Deitel to be identified as the authors of this work have been asserted by them in accordance with the Copyright, Designs and Patents Act 1988 Authorized adaptation from the United States edition, entitled C++ How to Program,10th Edition, ISBN 9780134448237, by Paul Deitel and Harvey Deitel published by Pearson Education © 2017 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 either the prior written permission of the publisher or a license permitting restricted copying in the United Kingdom issued by the Copyright Licensing Agency Ltd, Saffron House, 6–10 Kirby Street, London EC1N 8TS All trademarks used herein are the property of their respective owners The use of any trademark in this text does not vest in the author or publisher any trademark ownership rights in such trademarks, nor does the use of such trademarks imply any affiliation with or endorsement of this book by such owners British Library Cataloguing-in-Publication Data A catalogue record for this book is available from the British Library 10 ISBN 10: 1-292-15334-2 ISBN 13: 978-1-292-15334-6 Typeset by GEX Publishing Services Printed and bound in Malaysia In memory of Marvin Minsky, a founding father of the field of artificial intelligence It was a privilege to be your student in two graduate courses at M.I.T Every lecture you gave inspired your students to think beyond limits Harvey Deitel Trademarks DEITEL and the double-thumbs-up bug are registered trademarks of Deitel and Associates, Inc Carnegie Mellon Software Engineering Institute™ is a trademark of Carnegie Mellon University CERT® is registered in the U.S Patent and Trademark Office by Carnegie Mellon University UNIX is a registered trademark of The Open Group Microsoft and/or its respective suppliers make no representations about the suitability of the information contained in the documents and related graphics published as part of the services for any purpose All such documents and related graphics are provided “as is” without warranty of any kind Microsoft and/ or its respective suppliers hereby disclaim all warranties and conditions with regard to this information, including all warranties and conditions of merchantability, whether express, implied or statutory, fitness for a particular purpose, title and non-infringement In no event shall Microsoft and/or its respective suppliers be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of information available from the services The documents and related graphics contained herein could include technical inaccuracies or typographical errors Changes are periodically added to the information herein Microsoft and/or its respective suppliers may make improvements and/or changes in the product(s) and/or the program(s) described herein at any time Partial screen shots may be viewed in full within the software version specified Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A and other countries Screen shots and icons reprinted with permission from the Microsoft Corporation This book is not sponsored or endorsed by or affiliated with the Microsoft Corporation Throughout this book, trademarks are used Rather than put a trademark symbol in every occurrence of a trademarked name, we state that we are using the names in an editorial fashion only and to the benefit of the trademark owner, with no intention of infringement of the trademark Contents Chapters 23–26 and Appendices F–J are PDF documents posted online at the book’s Companion Website, which is accessible from http://www.pearsonglobaleditions.com/deitel See the inside front cover for more information Preface 23 Before You Begin 39 Introduction to Computers and C++ 41 1.1 1.2 1.3 Introduction Computers and the Internet in Industry and Research Hardware and Software 1.3.1 Moore’s Law 1.3.2 Computer Organization Data Hierarchy Machine Languages, Assembly Languages and High-Level Languages C and C++ Programming Languages Introduction to Object Technology Typical C++ Development Environment Test-Driving a C++ Application 1.10.1 Compiling and Running an Application in Visual Studio 2015 for Windows 1.10.2 Compiling and Running Using GNU C++ on Linux 1.10.3 Compiling and Running with Xcode on Mac OS X Operating Systems 1.11.1 Windows—A Proprietary Operating System 1.11.2 Linux—An Open-Source Operating System 1.11.3 Apple’s OS X; Apple’s iOS for iPhone®, iPad® and iPod Touch® Devices 1.11.4 Google’s Android The Internet and the World Wide Web Some Key Software Development Terminology C++11 and C++14: The Latest C++ Versions 1.4 1.5 1.6 1.7 1.8 1.9 1.10 1.11 1.12 1.13 1.14 42 43 45 45 46 47 50 51 52 54 57 60 60 65 67 72 72 72 73 73 74 76 78 Contents 1.15 1.16 Boost C++ Libraries Keeping Up to Date with Information Technologies 79 79 Introduction to C++ Programming, Input/Output and Operators 84 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 Introduction First Program in C++: Printing a Line of Text Modifying Our First C++ Program Another C++ Program: Adding Integers Memory Concepts Arithmetic Decision Making: Equality and Relational Operators Wrap-Up 85 85 89 90 94 95 99 103 Introduction to Classes, Objects, Member Functions and Strings 3.1 3.2 3.3 3.4 3.5 3.6 3.7 113 Introduction Test-Driving an Account Object 3.2.1 Instantiating an Object 3.2.2 Headers and Source-Code Files 3.2.3 Calling Class Account’s getName Member Function 3.2.4 Inputting a string with getline 3.2.5 Calling Class Account’s setName Member Function Account Class with a Data Member and Set and Get Member Functions 3.3.1 Account Class Definition 3.3.2 Keyword class and the Class Body 3.3.3 Data Member name of Type string 3.3.4 setName Member Function 3.3.5 getName Member Function 3.3.6 Access Specifiers private and public 3.3.7 Account UML Class Diagram Account Class: Initializing Objects with Constructors 3.4.1 Defining an Account Constructor for Custom Object Initialization 3.4.2 Initializing Account Objects When They’re Created 3.4.3 Account UML Class Diagram with a Constructor Software Engineering with Set and Get Member Functions Account Class with a Balance; Data Validation 3.6.1 Data Member balance 3.6.2 Two-Parameter Constructor with Validation 3.6.3 deposit Member Function with Validation 3.6.4 getBalance Member Function 3.6.5 Manipulating Account Objects with Balances 3.6.6 Account UML Class Diagram with a Balance and Member Functions deposit and getBalance Wrap-Up 114 115 115 116 116 117 117 118 118 119 119 120 122 122 123 124 125 126 128 128 129 129 131 131 131 132 134 134 Contents 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 4.10 4.11 4.12 4.13 4.14 4.15 Algorithm Development and Control Statements: Part Introduction Algorithms Pseudocode Control Structures 4.4.1 Sequence Structure 4.4.2 Selection Statements 4.4.3 Iteration Statements 4.4.4 Summary of Control Statements if Single-Selection Statement if…else Double-Selection Statement 4.6.1 Nested if…else Statements 4.6.2 Dangling-else Problem 4.6.3 Blocks 4.6.4 Conditional Operator (?:) Student Class: Nested if…else Statements while Iteration Statement Formulating Algorithms: Counter-Controlled Iteration 4.9.1 Pseudocode Algorithm with Counter-Controlled Iteration 4.9.2 Implementing Counter-Controlled Iteration 4.9.3 Notes on Integer Division and Truncation 4.9.4 Arithmetic Overflow 4.9.5 Input Validation Formulating Algorithms: Sentinel-Controlled Iteration 4.10.1 Top-Down, Stepwise Refinement: The Top and First Refinement 4.10.2 Proceeding to the Second Refinement 4.10.3 Implementing Sentinel-Controlled Iteration 4.10.4 Converting Between Fundamental Types Explicitly and Implicitly 4.10.5 Formatting Floating-Point Numbers 4.10.6 Unsigned Integers and User Input Formulating Algorithms: Nested Control Statements 4.11.1 Problem Statement 4.11.2 Top-Down, Stepwise Refinement: Pseudocode Representation of the Top 4.11.3 Top-Down, Stepwise Refinement: First Refinement 4.11.4 Top-Down, Stepwise Refinement: Second Refinement 4.11.5 Complete Second Refinement of the Pseudocode 4.11.6 Program That Implements the Pseudocode Algorithm 4.11.7 Preventing Narrowing Conversions with List Initialization Compound Assignment Operators Increment and Decrement Operators Fundamental Types Are Not Portable Wrap-Up 143 144 145 145 146 146 148 148 149 149 150 151 153 153 154 155 157 159 159 160 162 162 163 163 164 164 166 169 170 170 171 171 172 172 172 173 174 175 176 177 180 180 1060 Index output (cont.) floating-point value 621, 633 format of floating-point numbers 637 integers 621 standard data types 621 uppercase letters 621 output device 46 output iterator 704, 705, 706, 754, 763, 776, 779 output sequence 702 output stream 713 output to string in memory 262 output unit 46 outputting to strings in memory 927 overflow_error exception 816 overhead of a function call 1024 overload 94, 288 [] operator 512 + 494 > 291 addition assignment operator (+=) 502 addition operator (+) 493 assignment (=) operator 512, 518 binary operator < 495 binary operators 494, 495 cast operator function 521 constructor 444 constructors 565 equality operator (==) 512, 519 function 289, 833 function call operator () 525, 530 function definitions 289 increment operator 502 inequality operator 512, 519 operator += 505 operator[] member function 519 operators 291 overload (cont.) parentheses, () 784 postfix increment operator 501, 502, 506 prefix and postfix decrement operators 500 prefix and postfix increment operators 500 prefix increment operator 502, 506 resolution 833 stream insertion and stream extraction operators 495, 497, 501, 505, 511, 512, 516 subscript operator 512, 519 template functions 833 the stream insertion operator 683 unary operator ! 500 overloaded >) 488, 945 right shift with sign extension assignment operator (>>=) 953 right stream manipulator 209, 632, 634 right subtree 863, 866, 869, 870 right-to-left associativity 179 right triangle 196 right value 233 rightmost (trailing) arguments 287 right-shift operator (>>) 945, 946, 952, 989 right-shifting a signed value is machine dependent 953 right-to-left associativity 103 rise-and-shine algorithm 145 Ritchie, Dennis 51 robot 44 robust application 798, 803 Roku (Internet TV) 44 rolling dice 264, 268 rolling two dice 370 root node 863, 869 root node of the left subtree 863 root node of the right subtree 863 rotate algorithm 788 rotate_copy algorithm 788 round a floating-point number for display purposes 170 rounding a number 210 rounding numbers 162, 170, 255 Rounding Numbers exercise 313 row subscript 348 rows 347 RTTI (runtime type information) 607, 611 Ruby on Rails 54 Ruby programming language 54 rule of thumb (heuristic) 228 rules for forming structured programs 234 rules of operator precedence 96 running total 164 runtime error 60 runtime type information (RTTI) 607, 611, 614 runtime_error class 799, 807, 816 what function 804 1065 rvalue ("right value") 233, 284, 512 S SaaS (Software as a Service) 77 SalariedEmployee class header 594 SalariedEmployee class implementation file 595 savings account 207 Scala 54 scaling factor 263, 267 scanning images 46 scientific notation 170, 621, 638 School Nutrition Programs exercise 197 scientific stream manipulator 633, 637 scope 273 class 273 file 273 function 273 function prototype 273 namespace 273 of a symbolic constant or macro 1025 of a variable 204 of an identifier 126 scope resolution operator (::) 270 scope resolution operator (::) 431, 470, 828 scoped enumeration (enum class) 270 scoping example 275 screen 45, 46, 59, 86 screen-manager program 573 scripting language 50 scrutinize data 432 SDK (Software Development Kit) 77 search a linked list 842, 879 search algorithm 788 search algorithms 882 binary search 886 linear search 883 1066 Index search functions of the stringhandling library 975 search key 721, 882, 883, 886 search_n algorithm 788 searching 697, 766, 838 searching arrays 346 searching blocks of memory 979 searching data 882 Searching for Characters exercise 991 Searching for Substrings exercise 991 searching performance 879 searching strings 963, 970 second data member of pair 725 second-degree polynomial 98 second refinement in topdown, stepwise refinement 173 secondary storage 46 secondary storage devices 656 CD 656 DVD 656 flash drive 656 hard disk 656 tape 656 secondary storage unit 47 second-degree polynomial 98 security flaws 335 seed 267 nondeterministic 765 seed function rand 266 seed the random-number generator 765 seek direction 663 seek get 663 seek put 663 seekg function of istream 663, 682 seekp function of ostream 663, 673 select a substring 525 selection 149, 164, 237, 238 selection sort 891, 895, 901, 902 selection sort algorithm 893 selection sort efficiency 893 selection sort with call-byreference 893 selection statement 146, 148 if 148, 150, 238, 239 if else 148, 150, 151, 168, 238 switch 148, 225, 238 self assignment 465, 518 self documenting 92 self-referential class 839, 840 semicolon (;) 87, 102, 1022 semicolon that terminates a structure definition 941 send a message to an object 55 Sentence letter statistics exercise 936 sentinel-controlled iteration 247 sentinel-controlled repetition 164, 165, 167, 168 sentinel value 163, 165, 168 separate interface from implementation 428 Separating Digits exercise 315 Separating Class Interface from Implementation exercise 480 sequence 146, 149, 236, 238, 347, 702, 772, 774 sequence container 698, 705, 707, 715, 718 back function 714 empty function 715 front function 714 insert function 715 sequence of random numbers 266 sequence-structure activity diagram 147 sequential execution 146 sequential file 656, 657, 661, 667, 668 serialized object 684 Server Income Ranges exercise 369 header 261 associative container 721, 725 set function 461 header 722, 725 set_intersection 779 set_new_handler function 809, 811 set of recursive calls to method Fibonacci 299 set operations of the Standard Library 777 set_difference algorithm 777, 779, 788 set_intersection algorithm 777, 779, 788 set_new_handler specifying the function to call when new fails 811 set set_symmetric_difference algorithm 777, 779, 788 algorithm 777, 779, 788 setbase stream manipulator 628 setfill stream manipulator 421, 432, 634, 635 setprecision stream manipulator 170, 628 Setting bits in an integer exercise 989 setw parameterized stream manipulator 209, 327, 406, 498, 630, 634 shadow 463 Shakespeare, William 993 Shape class hierarchy 540, 569 shape of a tree 879 shell prompt on Linux 60 shift a range of numbers 263 shifted, scaled integers 264 shifted, scaled integers produced by + rand() % 263 shiftingValue 267 “shipping” section of the computer 46 shopping list 157 short-circuit evaluation 230 set_union Index stream manipulator 633, 637 showpoint stream manipulator 170, 633 showpos stream manipulator 421, 633, 635 shrink_to_fit member function of classes vector and deque 712 shuffle algorithm 763, 765, 788 shuffle cards 988 shuffling algorithm 943 sibling 863 side effect 282 of an expression 274, 282, 299 sides of a right triangle 196 sides of a triangle 195 Sieve of Eratosthenes exercise 375, 746 sign extension 946 sign left justified 632 signal value 163 signature 259, 289, 500 signatures of overloaded prefix and postfix increment operators 501 significant digits 633 simple condition 228 Simple Decryption 937 Simple dictionary exercise 693 simplest activity diagram 234, 236 Simpletron Machine Language (SML) 422, 839 Simpletron Simulator exercise 422, 839 simulation 419 Simulation: Tortoise and the Hare exercise 414 sin function 255 sine 255 single-argument constructor 523, 524 single entry point 234 single-entry/single-exit control statements 149, 234 showbase single exit point 234 single inheritance 539 single-line comment 86 single-precision floating-point number 209 single quote 88 single quote (') 404 single-selection statement 148, 150, 238 if 150 singly linked list 698, 716, 853 six-sided die 263 size function of string 672 size member function of array 325 size member function of class string 218, 911 size member function of containers 699 size member function of priority_queue 734 size member function of queue 733 size member function of stack 731 size member function of vector 360 size of a string 917 size of a variable 94 size of an array 396 size_t 327, 669 size_t type 396 size_type 701 sizeof 975, 1025 sizeof operator 396, 397, 463, 675 used to determine standard data type sizes 397 sizeof operator when applied to an array name returns the number of bytes in the array 396 skipping whitespace 627, 632 skipws stream manipulator 632 small circles in the UML 147 smallest 309 smallest of several integers 246 1067 smart pointer 26, 79 make_unique function template 813, 815 smartphone 43, 74 SML 417 SML operation code 417 SMS Language exercise 938 software 42, 45 Software as a Service (SaaS) 77 Software Development Kit (SDK) 77 software engineering data hiding 122 reuse 116, 427 separate interface from implementation 428 software reuse 52, 253, 825 solid circle in the UML 147 solid circle surrounded by a hollow circle in the UML 147 solution 61 Solution Explorer 63 sort algorithm 346, 766, 770, 788, 850 sort algorithms bubble sort 905 bucket sort 905 insertion sort 891, 893 merge sort 895 quicksort 906 selection sort 893 sort key 882 sort member function of list 719 sort_heap algorithm 788 sorting 657, 697, 766, 838 algorithms 787, 890 arrays 346 arrays 890 data 882 sort order 770, 774 strings 262 source code 57 source-code file 116 space–time trade-off 710 spaces for padding 635 space-time trade-off 677 1068 Index Spam Scanner 938 speaking to a computer 46 special character 405 special characters 91 Special Section: Building Your Own Computer 416 special symbol 48 specialization of a class template 620 spelling checker 997 Splitting a list exercise 875 spiral 297 splice member function of list 719 splice_after member function of class template forward_list 719 split the array in merge sort 895 spooler 860 Spot the bug exercise 935 sqrt function of header 255 square 194 square function 260 Square of Asterisks exercise 194 square root 255, 628 srand function 266, 267 header 262, 432, 927, 432, 927 stable_partition algorithm 788 stable_sort algorithm 788 header 261 stack 277, 697, 825, 838, 840, 853, 857 stack adapter class 731 empty function 731 pop function 731 push function 731 size function 731 top function 731 Stack class template 826, 832, 858, 879 definition 856 definition with a composed List object 859 stack frame 277 header 731 stack overflow 278, 294 stack unwinding 803, 806, 808, 822 Stack< double > 828, 832, 857 stack 832 Stack 830 stacking building blocks 238 stacking control statements 239 stacking rule 236 stacks used by compilers 875 standard data type sizes 397 standard error stream (cerr) 59 standard exception classes 816 standard input stream (cin) 59, 93, 620, 656 Standard Library 253 class string 489 container classes 698 deque class template 720 exception classes 815 exception hierarchy 815 function sort 890 headers 262, 1022 list class template 716 map class template 729 multimap class template 727 multiset class template 722 priority_queue adapter class 734 queue adapter class templates 733 set class template 726 stack adapter class 731 vector class template 708 standard output stream (cout) 59, 87, 620, 656 standard stream libraries 619 Standard Template Library 696 “warehouse” section of the computer 47 Start Page 61 state bits 641, 643 statement 87, 121 statement spread over several lines 102 statement terminator (;) 87 Statements 165 statements break 224, 226, 227, 248 continue 226, 248 control statement 145, 146, 149, 150 control-statement nesting 149 control-statement stacking 149 while 148, 219, 220, 238 double selection 148, 172 empty 154 for 148, 201, 205, 207, 209, 238 if 99, 102, 148, 150, 238, 239 if else 148, 150, 151, 168, 238 iteration 146, 157 looping 148 multiple selection 148 nested control statements 171 nested if else 151, 193 repetition 148 return 88, 254 selection 146, 148 single selection 148 switch 148, 220, 225, 238 throw 432 try 362 while 148, 157, 158, 161, 162, 168, 201, 238, 239 static array initialization 336 static array initialization and automatic array initialization 336 static binding 581 static data member 344, 469, 470 save storage 469 Index data member (cont.) tracking the number of objects of a class 472 static data member to maintain a count of the number of objects of a class 470 static keyword 274 static local object 446, 448, 449 static local variable 274, 275, 277, 336, 754 static member 470 static member function 470 static_cast 232 static_cast (compile-time type-checked cast) 326 static_cast operator 169, 180 Static vs dynamic casting exercise 614 std namespace 910 std::cin 93 std::cout 87 std::endl stream manipulator 94 STDC predefined symbolic constant 1028 header 261, 799, 816 StepStone 73 Sticky and non-sticky I/O settings exercise 652 sticky settings for streams 209, 231, 432 STL 696 STL exception types 714 stod function 931 stof function 931 stoi function 931 stol function 931 stold function 931 stoll function 931 storage alignment 941 storage unit 957 storage-unit boundary 957 store a lambda in a variable 769 stoul function 931 static function 931 member function of class ostringstream 432, 928, 929 straight-line form 96, 97 strcat function of header 963, 965 strchr function of header 975 strcmp function of header 963, 966 strcpy function of header 963, 964 strcspn function of header 975, 976 stream sticky settings 209, 231, 432 stream base 628 stream extraction operator >> ("get from") 93, 102, 291, 488, 495, 516, 620, 622, 683 stream input/output 86 stream insertion operator

Ngày đăng: 04/03/2019, 10:44

Từ khóa liên quan

Mục lục

  • Cover

  • Title Page

  • Copyright Page

  • Contents

  • Preface

  • Before You Begin

  • 1 Introduction to Computers and C++ 41

    • 1.1 Introduction 42

    • 1.2 Computers and the Internet in Industry and Research 43

    • 1.3 Hardware and Software 45

      • 1.3.2 Computer Organization 46

      • 1.4 Data Hierarchy 47

      • 1.5 Machine Languages, Assembly Languages and High-Level Languages 50

      • 1.6 C and C++ 51

      • 1.7 Programming Languages 52

      • 1.8 Introduction to Object Technology 54

      • 1.9 Typical C++ Development Environment 57

      • 1.10 Test-Driving a C++ Application 60

        • 1.10.1 Compiling and Running an Application in Visual Studio 2015 for Windows 60

        • 1.10.2 Compiling and Running Using GNU C++ on Linux 65

        • 1.10.3 Compiling and Running with Xcode on Mac OS X 67

        • 1.11 Operating Systems 72

          • 1.11.1Windows—A Proprietary Operating System 72

          • 1.11.2 Linux—An Open-Source Operating System 72

Tài liệu cùng người dùng

Tài liệu liên quan