C++

Информатика и компютърни науки Книга или учебник

C++ Without Fear
Second Edition

This page intentionally left blank

C++ Without Fear
Second Edition
A Beginner’s Guide That
Makes You Feel Smart
Brian Overland
Upper Saddle River, NJ • Boston • Indianapolis • San Francisco
New York • Toronto • Montreal • London • Munich • Paris • Madrid
Capetown • Sydney • Tokyo • Singapore • Mexico City

Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in this book, and the publisher was aware
of a trademark claim, the designations have been printed with initial capital letters or in all capitals.
The author and publisher have taken care in the preparation of this book, but make no expressed
or implied warranty of any kind and assume no responsibility for errors or omissions. No liability
is assumed for incidental or consequential damages in connection with or arising out of the use of
the information or programs contained herein.
The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases
or special sales, which may include electronic versions and/or custom covers and content particu-
lar to your business, training goals, marketing focus, and branding interests. For more informa-
tion, please contact:
U.S. Corporate and Government Sales
(800) 382-3419
corpsales@pearsontechgroup.com
For sales outside the United States please contact:
International Sales
international@pearson.com
Visit us on the Web: informit.com/ph
Library of Congress Cataloging-in-Publication Data
Overland, Brian R.
C++ without fear : a beginner's guide that makes you feel smart /
Brian Overland.—2nd ed.
p. cm.
Includes index.
ISBN 978-0-13-267326-6 (pbk. : alk. paper)
1. C++ (Computer program language) I. Title.
QA76.73.C153O838 2011
005.13'3—dc22
2011004218
Copyright © 2011 Pearson Education, Inc.
All rights reserved. Printed in the United States of America. This publication is protected by copy-
right, and permission must be obtained from the publisher prior to any prohibited reproduction,
storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical,
photocopying, recording, or likewise. For information regarding permissions, write to:
Pearson Education, Inc.
Rights and Contracts Department
501 Boylston Street, Suite 900
Boston, MA 02116
Fax: (617) 671-3447
ISBN-13: 978-0-13-267326-6
ISBN-10: 0-13-267326-6
Text printed in the United States on recycled paper at Edwards Brothers in Ann Arbor, Michigan.
First printing, April 2011

For Colin

This page intentionally left blank

vii
Preface xxiii
About This Book: How It’s Different xxiii
Onward to the Second Edition xxiv
“Where Do I Begin?” xxv
Icons, Icons, Who’s Got the Icons? xxv
What Is Not Covered? xxvi
Getting Started with C++: A Free Compiler xxvii
A Final Note: Have Fun! xxvii
Acknowledgments xxix
About the Author xxxi
Chapter 1
Your First C++ Programs 1
Thinking Like a Programmer 1
Computers Do Only What You Tell Them 1
Determine What the Program Will Do 1
Write the Equivalent C++ Statements 2
Interlude How “Smart” Are Computers, Really? 4
Some Nerdy Definitions—A Review 4
What’s Different About C++? 7
Building a C++ Program 8
Enter the Program Statements 8
Build the Program (Compile and Link) 8
Contents

Test the Program 9
Revise as Needed 9
Installing Your Own C++ Compiler 10
Example 1.1. Print a Message 11
If You’re Using the Dev-C++ Environment 12
If You’re Using Microsoft Visual Studio 12
How It Works 13
Exercises 15
Interlude What about the #include and using? 15
Advancing to the Next Print Line 16
Example 1.2. Print Multiple Lines 16
How It Works 17
Exercises 18
Interlude What Is a String? 18
Storing Data: C++ Variables 19
Introduction to Data Types 20
Interlude Why Double Precision, Not Single? 22
Example 1.3. Convert Temperatures 22
How It Works 24
Optimizing the Program 26
Exercises 28
A Word about Variable Names and Keywords 28
Exercise 29
Chapter 1 Summary 30
Chapter 2
Decisions, Decisions 33
But First, a Few Words about Data Types 33
Decision Making in Programs 34
Interlude What about Artificial Intelligence (AI)? 35
if and if-else 35
Interlude Why Two Operators (= and ==)? 38
Example 2.1. Odd or Even? 39
How It Works 40
Optimizing the Code 42
Exercise 42
Introducing Loops 43
Interlude Infinite Loopiness 46
Example 2.2. Print 1 to N 46
viii Contents

How It Works 47
Optimizing the Program 49
Exercises 49
True and False in C++ 50
Interlude The bool Data Type 51
The Increment Operator (++) 51
Statements vs. Expressions 52
Introducing Boolean (Short-Circuit) Logic 53
Interlude What Is “true”? 55
Example 2.3. Testing a Person’s Age 55
How It Works 56
Exercise 56
Introducing the Math Library 57
Example 2.4. Prime-Number Test 57
How It Works 59
Optimizing the Program 60
Exercise 60
Example 2.5. The Subtraction Game (NIM) 60
How It Works 63
Exercises 63
Chapter 2 Summary 64
Chapter 3
The Handy, All-Purpose “for” Statement67
Loops Used for Counting 67
Introducing the “for” Loop 68
A Wealth of Examples 70
Interlude Does “for” Always Behave Like “while”? 71
Example 3.1. Printing 1 to N with “for” 72
How It Works 73
Exercises 73
Compound Statements (Blocks) with “for” 74
Declaring Loop Variables on the Fly 74
Example 3.2. Prime-Number Test with “for” 75
How It Works 77
Exercise 79
Comparative Languages 101: The Basic “For” Statement 79
Chapter 3 Summary 80
ixContents

Chapter 4Functions: Many Are Called 83
The Concept of Function 83
The Basics of Using Functions 85
Step 1: Declare (Prototype) the Function 85
Step 2: Define the Function 85
Step 3: Call the Function 86
Example 4.1. The avg() Function 87
How It Works 88
Function Call a Function! 89
Exercises 90
Example 4.2. Prime-Number Function 90
How It Works 92
Exercises 93
Local and Global Variables 93
Interlude Why Global Variables at All? 95
Recursive Functions 95
Example 4.3. Prime Factorization 96
How It Works 98
Interlude Interlude for Math Junkies 100
Exercises 101
Example 4.4. Euclid’s Algorithm for GCF 101
How It Works 103
Interlude Who Was Euclid? 104
Exercises 105
Interlude Interlude for Math Junkies: Rest of the Proof 105
Example 4.5. Beautiful Recursion: Tower of Hanoi 106
How It Works 109
Exercises 110
Example 4.6. Random-Number Generator 110
How It Works 111
Exercises 113
Games and More Games 113
Chapter 4 Summary 115
Chapter 5
Arrays: All in a Row... 117
A First Look at C++ Arrays 117
Initializing Arrays 119
x Contents

Zero-Based Indexing 119
Interlude Why Use Zero-Based Indexes? 120
Example 5.1. Print Out Elements 121
How It Works 121
Exercises 122
Example 5.2. How Random Is Random? 123
How It Works 125
Exercises 127
Strings and Arrays of Strings 128
Example 5.3. Card Dealer #1 129
How It Works 131
Exercise 132
Example 5.4. Card Dealer #2 132
How It Works 134
Exercise 135
Example 5.5. Card Dealer #3 136
How It Works 138
Optimizing the Program 140
Exercise 141
A Word to the Wise 141
2-D Arrays: Into the Matrix 142
Chapter 5 Summary 143
Chapter 6
Pointers: Getting a Handle on Data145
What the Heck Is a Pointer, Anyway? 145
The Concept of Pointer 146
Interlude What Do Addresses Look Like? 147
Declaring and Using Pointers 148
Example 6.1. Print Out Addresses 151
Example 6.2. The double_it Function 152
How It Works 153
Exercises 154
Swap: Another Function Using Pointers 155
Example 6.2. Array Sorter 156
How It Works 160
Exercises 161
Pointer Arithmetic 161
xiContents

Pointers and Array Processing 163
Example 6.3. Zero Out an Array 165
How It Works 166
Writing More Compact Code 166
Exercises 167
Chapter 6 Summary 168
Chapter 7
Strings: Analyzing the Text 169
Text Storage on the Computer 169
Interlude How Does the Computer Translate Programs? 170
It Don’t Mean a Thing If It Ain’t Got That String 171
String-Manipulation Functions 172
Example 7.1. Building Strings 174
How It Works 175
Exercises 176
Interlude What about Escape Sequences? 177
Reading String Input 178
Example 7.2. Get a Number 180
How It Works 181
Exercise 183
Example 7.3. Convert to Uppercase 183
How It Works 184
Exercises 185
Individual Characters vs. Strings 185
Example 7.4. Breaking Up Input with Strtok 186
How It Works 188
Exercises 188
The New C++ String Type 189
Include String-Class Support 189
Declare and Initialize Variables of Type string 189
Working with Variables of Type string 190
Input and Output 191
Example 7.5. Building Strings with the string Type 191
How It Works 192
Exercises 193
Other Operations on the string Type 193
Chapter 7 Summary 194
xii Contents

Chapter 8Files: Electronic Storage 197
Introducing File-Stream Objects 197
How to Refer to Disk Files 199
Example 8.1. Write Text to a File 200
How It Works 201
Exercises 203
Example 8.2. Display a Text File 203
How It Works 204
Exercises 205
Text Files vs. “Binary” Files 206
Interlude Are “Binary Files” Really More Binary? 208
Introducing Binary Operations 208
Example 8.3. Random-Access Write 211
How It Works 213
Exercises 214
Example 8.4. Random-Access Read 214
How It Works 216
Exercises 217
Chapter 8 Summary 217
Chapter 9
Some Advanced Programming Techniques221
Command-Line Arguments 221
Example 9.1. Display File from Command Line 223
How It Works 224
Improving the Program 225
Interlude The Virtue of Predefined Constants 226
Exercises 226
Function Overloading 227
Interlude Overloading and Object Orientation 228
Example 9.2. Printing Different Types of Arrays 228
How It Works 230
Exercise 230
The do-while Loop 230
The switch-case Statement 232
Multiple Modules 234
Exception Handling: I Take Exception to That! 237
Say Hello to Exceptions 237
xiiiContents

Handling Exceptions: A First Attempt 238
Introducing try-catch Exception Handling 238
Chapter 9 Summary 240
Chapter 10
New Features of C++0x 243
Overview of C++0x Features 243
The long long Type (not long long long) 244
Interlude Why a “Natural” Integer? 246
Working with 64-Bit Literals (Constants) 246
Accepting long long Input 247
Formatting long long Numbers 248
Example 10.1. Fibonacci: A 64-Bit Example 250
How It Works 253
Exercises 254
Localizing Numbers 254
Interlude Who Was Fibonacci? 255
Range-Based “for” (For Each) 256
Example 10.2. Setting an Array with Range-Based “for” 258
How It Works 260
Exercises 260
The auto and decltype Keywords 261
The nullptr Keyword 262
Strongly Typed Enumerations 263
enum Classes in C++0x 265
Extended enum Syntax: Controlling Storage 266
Example 10.3. Rock, Paper, Scissors Game 267
How It Works 269
A More Interesting Game 271
Exercises 272
Raw String Literals 273
Chapter 10 Summary 273
Chapter 11
Introducing Classes: The Fraction Class277
Object Orientation: Quasi-Intelligent Data Types 277
Interlude OOP…Is It Worth It? 278
Point: A Simple Class 279
Interlude Interlude for C Programmers: Structures and Classes 281
xiv Contents

Private: Members Only (Protecting the Data) 281
Exmple 11.1. Testing the Point Class 284
How It Works 286
Exercises 286
Introducing the Fraction Class 286
Inline Functions 289
Find the Greatest Common Factor 291
Find the Lowest Common Denominator 292
Example 11.2. Fraction Support Functions 293
How It Works 294
Exercises 296
Example 11.3. Testing the Fraction Class 296
How It Works 299
Interlude A New Kind of #include? 299
Exercise 300
Example 11.4. Fraction Arithmetic: add and mult 300
How It Works 304
Exercises 305
Chapter 11 Summary 305
Chapter 12
Constructors: If You Build It…307
Introducing Constructors 307
Multiple Constructors (Overloading) 309
C++0x Only: Initializing Members within a Class 309
The Default Constructor—and a Warning 310
Interlude Is C++ Out to Trick You with the Default Constructor? 312
C++0x Only: Delegating Constructors 313
C++0x Only: Consistent Initialization 314
Example 12.1. Point Class Constructors 315
How It Works 316
Exercises 317
Example 12.2. Fraction Class Constructors 317
How It Works 320
Exercises 320
Reference Variables and Arguments (&) 321
The Copy Constructor 323
Interlude The Copy Constructor and References 325
xvContents

Example 12.3. Fraction Class Copy Constructor 325
H

Преглед на първите от 620 страници - останалите след изтегляне

Описание

Учебник по С++ на английски език Дисциплина: Програмиране

0 коментара

Все още няма коментари. Бъдете първият, който ще коментира.

За да коментирате, трябва да сте влезли в профила си.

Влезте