Tải bản đầy đủ (.pdf) (988 trang)

975 ivor hortons beginning visual c++ 2012

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (17.53 MB, 988 trang )

www.it-ebooks.info


www.it-ebooks.info
ffirs.indd ii

17/09/12 6:32 PM


IVOR HORTON’S
BEGINNING VISUAL C ++® 2012
INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxv
CHAPTER 1

Programming with Visual C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

CHAPTER 2

Data, Variables, and Calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

CHAPTER 3

Decisions and Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

CHAPTER 4

Arrays, Strings, and Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

CHAPTER 5

Introducing Structure into Your Programs . . . . . . . . . . . . . . . . . . . . . . . . 189



CHAPTER 6

More about Program Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231

CHAPTER 7

Defining Your Own Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277

CHAPTER 8

More on Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333

CHAPTER 9

Class Inheritance and Virtual Functions . . . . . . . . . . . . . . . . . . . . . . . . . 441

CHAPTER 10

The Standard Template Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491

CHAPTER 11

Windows Programming Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601

CHAPTER 12

Windows Programming
with the Microsoft Foundation Classes (MFC) . . . . . . . . . . . . . . . . . . . . 635


CHAPTER 13

Working with Menus and Toolbars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659

CHAPTER 14

Drawing in a Window. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685

CHAPTER 15

Improving the View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 739

CHAPTER 16

Working with Dialogs and Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 769

CHAPTER 17

Storing and Printing Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 815

CHAPTER 18

Programming Windows 8 Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 849

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 905

www.it-ebooks.info
ffirs.indd i

17/09/12 6:32 PM



www.it-ebooks.info
ffirs.indd ii

17/09/12 6:32 PM


IVOR HORTON’S
BEGINNING
®

Visual C ++ 2012

www.it-ebooks.info
ffirs.indd iii

17/09/12 6:32 PM


www.it-ebooks.info
ffirs.indd iv

17/09/12 6:32 PM


IVOR HORTON’S
BEGINNING
®


Visual C++ 2012

Ivor Horton

John Wiley & Sons, Inc.

www.it-ebooks.info
ffirs.indd v

17/09/12 6:32 PM


Ivor Horton’s Beginning Visual C++® 2012
Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com

Copyright © 2012 by Ivor Horton
Published by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-118-36808-4
ISBN: 978-1-118-43941-8 (ebk)
ISBN: 978-1-118-41703-4 (ebk)
ISBN: 978-1-118-43431-4 (ebk)

Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,

electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108
of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization
through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers,
MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the
Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011,
fax (201) 748-6008, or online at />Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with
respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including
without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold
with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services.
If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to
in this work as a citation and/or a potential source of further information does not mean that the author or the publisher
endorses the information the organization or Web site may provide or recommendations it may make. Further, readers
should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was
written and when it is read.
For general information on our other products and services please contact our Customer Care Department within the
United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with
standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to
media such as a CD or DVD that is not included in the version you purchased, you may download this material at
. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2012946046
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are
trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affi liates, in the United States and other countries, and may not be used without written permission. Visual C++ is a registered trademark of Microsoft Corporation.
All other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any
product or vendor mentioned in this book.

www.it-ebooks.info
ffirs.indd vi

17/09/12 6:32 PM



This book is for my dear wife, Eve, who for so many
years has given me unconditional support and love in
whatever I choose to do. I could not have written this
without her.

www.it-ebooks.info
ffirs.indd vii

17/09/12 6:32 PM


www.it-ebooks.info
ffirs.indd viii

17/09/12 6:32 PM


ABOUT THE AUTHOR

IVOR HORTON graduated as a mathematician and was lured into information

technology by promises of great rewards for very little work. In spite of the
reality usually being a great deal of work for relatively modest rewards, he has
continued to work with computers to the present day. He has been engaged at
various times in programming, systems design, consultancy, and the management and implementation of projects of considerable complexity.
Horton has many years of experience in the design and implementation of computer systems applied to engineering design and manufacturing operations in a variety of industries.
He has considerable experience in developing occasionally useful applications in a wide variety of
programming languages, and in teaching primarily scientists and engineers to do likewise. He has

been writing books on programming for many years, and his currently published works include
tutorials on C, C++, and Java. At the present time, when he is not writing programming books or
providing advice to others, he spends his time fishing, traveling, and enjoying life in general.

www.it-ebooks.info
ffirs.indd ix

17/09/12 6:32 PM


www.it-ebooks.info
ffirs.indd x

17/09/12 6:32 PM


ABOUT THE TECHNICAL EDITOR

MARC GREGOIRE is a software engineer from Belgium. He graduated from the

Catholic University of Leuven, Belgium, with a degree in “Burgerlijk ingenieur in
de computer wetenschappen” (equivalent to master of science in engineering
in computer science). The year after, he received the cum laude degree of master in
artificial intelligence at the same university. After his studies, Marc started working
for a big software consultancy company called Ordina Belgium. As a consultant,
he worked for Siemens and Nokia Siemens Networks on critical 2G and 3G
software running on Solaris for big telecom operators. This required working in international teams
stretching from South America and USA to EMEA and Asia. Now, Marc is working for Nikon
Metrology on 3D scanning software.
His main expertise is C/C++, and specifically Microsoft VC++ and the MFC framework. Next to

C/C++, Marc also likes C# and uses PHP for creating web pages. In addition to his main interest for
Windows development, he also has experience in developing C++ programs running 24/7 on Linux
platforms; for example, EIB home automation-controlling and monitoring software.
Since April 2007, he received the yearly Microsoft MVP (Most Valuable Professional) award for his
Visual C++ expertise.
Marc is the founder of the Belgian C++ Users Group (www.becpp.org) and an active member on the
CodeGuru forum (as Marc G). He also creates freeware and shareware programs that are distributed
through his website at www.nuonsoft.com , and maintains a blog on www.nuonsoft.com/blog/.

www.it-ebooks.info
ffirs.indd xi

17/09/12 6:32 PM


www.it-ebooks.info
ffirs.indd xii

17/09/12 6:32 PM


CREDITS

Executive Editor

Production Manager

Robert Elliott

Tim Tate


Project Editor

Vice President and Executive Group
Publisher

Ed Connor

Richard Swadley

Technical Editor
Vice President and Executive Publisher

Marc Gregoire

Neil Edde

Production Editor
Associate Publisher

Daniel Scribner

Jim Minatel

Copy Editor
Project Coordinator, Cover

Kim Cofer

Katie Crocker


Editorial Manager
Mary Beth Wakefield

Proofreaders

Freelancer Editorial Manager

James Saturnio, Word One
Sarah Kaikini, Word One

Rosemarie Graham

Indexer
Associate Director of Marketing

Ron Strauss

David Mayhew

Cover Designer
Marketing Manager

Ryan Sneed

Ashley Zurcher

Cover Image
Business Manager


© Kyu Oh / iStockPhoto

Amy Knies

www.it-ebooks.info
ffirs.indd xiii

17/09/12 6:32 PM


www.it-ebooks.info
ffirs.indd xiv

17/09/12 6:32 PM


ACKNOWLEDGMENTS

THE AUTHOR IS ONLY ONE MEMBER of the large team of people necessary to get a book into print.
I’d like to thank the John Wiley & Sons and Wrox Press editorial and production teams for their
help and support throughout.

I would particularly like to thank my technical editor, Marc Gregoire, for doing such a fantastic
job of reviewing the text and checking out all the code fragments and examples. He has an uncanny
knack for fi nding my errors, and his many constructive comments and suggestions have undoubtedly made the book a much better tutorial.

www.it-ebooks.info
ffirs.indd xv

17/09/12 6:32 PM



www.it-ebooks.info
ffirs.indd xvi

17/09/12 6:32 PM


CONTENTS

INTRODUCTION

xxxv

CHAPTER 1: PROGRAMMING WITH VISUAL C++

Learning with Visual C++
Writing C++ Applications
Learning Desktop Applications Programming
Learning C++
Console Applications
Windows Programming Concepts

What Is the Integrated Development Environment?
The Editor
The Compiler
The Linker
The Libraries

1


1
2
3
3
4
4

5
6
6
6
6

Using the IDE

7

Toolbar Options
Dockable Toolbars
Documentation
Projects and Solutions
Defining a Project
Debug and Release Versions of Your Program
Executing the Program
Dealing with Errors
Setting Options in Visual C++
Creating and Executing Windows Applications
Creating an MFC Application
Building and Executing the MFC Application


Summary

8
9
10
10
10
15
16
18
19
20
20
22

23

CHAPTER 2: DATA, VARIABLES, AND CALCULATIONS

The Structure of a C++ Program
Program Comments
The #include Directive — Header Files
Namespaces and the Using Declaration
The main() Function
Program Statements

25

26

31
32
33
34
34

www.it-ebooks.info
ftoc.indd xvii

17/09/12 10:42 AM


CONTENTS

Whitespace
Statement Blocks
Automatically Generated Console Programs
Precompiled Header Files
Main Function Names

Defining Variables

37
37
37
38
39

39


Naming Variables
Keywords in C++
Declaring Variables
Initial Values for Variables

Fundamental Data Types

39
40
41
41

42

Integer Variables
Character Data Types
Integer Type Modifiers
The Boolean Type
Floating-Point Types
Fundamental Types in C++
Literals
Defining Synonyms for Data Types

42
44
45
46
47
47
48

49

Basic Input/Output Operations

50

Input from the Keyboard
Output to the Command Line
Formatting the Output
Escape Sequences

50
50
51
53

Calculating in C++

55

The Assignment Statement
Arithmetic Operations
The const Modifier
Constant Expressions
Program Input
Calculating the Result
Displaying the Result
Calculating a Remainder
Modifying a Variable
The Increment and Decrement Operators

The Sequence of Calculation
Operator Precedence

Type Conversion and Casting
Type Conversion in Assignments
Explicit Type Conversion
Old-Style Casts

55
55
58
58
59
59
60
61
61
62
65
65

66
67
68
69

xviii

www.it-ebooks.info
ftoc.indd xviii


17/09/12 10:42 AM


CONTENTS

The auto Keyword
Discovering Types
The Bitwise Operators

69
70
70

The Bitwise AND
The Bitwise OR
The Bitwise Exclusive OR
The Bitwise NOT
The Bitwise Shift Operators

71
72
73
74
74

Introducing Lvalues and Rvalues
Understanding Storage Duration and Scope
Automatic Variables
Positioning Variable Declarations

Global Variables
Static Variables

Variables with Specific Sets of Values
Old Enumerations
Type-Safe Enumerations

76
77
78
80
80
84

85
85
87

Namespaces

90

Declaring a Namespace
Multiple Namespaces

91
92

Summary


93

CHAPTER 3: DECISIONS AND LOOPS

Comparing Values

97

97

The if Statement
Nested if Statements
The Extended if Statement
Nested if-else Statements
Logical Operators and Expressions
Logical AND
Logical OR
Logical NOT
The Conditional Operator
The switch Statement
Unconditional Branching

Repeating a Block of Statements
What Is a Loop?
Variations on the for Loop
Using the continue Statement
Floating-Point Loop Counters

99
100

102
104
106
107
107
108
109
111
115

115
116
118
122
126

xix

www.it-ebooks.info
ftoc.indd xix

17/09/12 10:42 AM


CONTENTS

The while Loop
The do-while Loop
The Range-Based for Loop
Nested Loops


Summary

126
128
129
130

133

CHAPTER 4: ARRAYS, STRINGS, AND POINTERS

Handling Multiple Data Values
of the Same Type
Arrays
Declaring Arrays
Initializing Arrays
Using the Range-Based for Loop
Character Arrays and String Handling
String Input
Using the Range-Based for Loop with Strings
Multidimensional Arrays
Initializing Multidimensional Arrays

Indirect Data Access

135

135
136

137
140
142
143
144
146
146
147

150

What Is a Pointer?
Declaring Pointers
The Address-Of Operator
Using Pointers
The Indirection Operator
Why Use Pointers?
Initializing Pointers
Pointers to char
The sizeof Operator
Constant Pointers and Pointers to Constants
Pointers and Arrays
Pointer Arithmetic
Using Pointers with Multidimensional Arrays
Pointer Notation with Multidimensional Arrays

Dynamic Memory Allocation
The Free Store, Alias the Heap
The new and delete Operators
Allocating Memory Dynamically for Arrays

Dynamic Allocation of Multidimensional Arrays

Using References

150
150
151
152
152
152
152
155
159
161
163
164
168
169

170
170
171
172
175

176

What Is a Reference?
Declaring and Initializing Lvalue References


176
176

xx

www.it-ebooks.info
ftoc.indd xx

17/09/12 10:42 AM


CONTENTS

Using References in a Range-Based for Loop
Rvalue References

Library Functions for Strings
Finding the Length of a Null-Terminated String
Joining Null-Terminated Strings
Copying Null-Terminated Strings
Comparing Null-Terminated Strings
Searching Null-Terminated Strings

Summary

177
178

178
179

179
181
182
183

185

CHAPTER 5: INTRODUCING STRUCTURE
INTO YOUR PROGRAMS

Understanding Functions

189

189

Why Do You Need Functions?
Structure of a Function
The Function Header
The Function Body
The return Statement
Alternative Function Syntax
Using a Function
Function Prototypes

Passing Arguments to a Function
The Pass-by-Value Mechanism
Pointers as Arguments to a Function
Passing Arrays to a Function
Passing Multidimensional Arrays to a Function

References as Arguments to a Function
Use of the const Modifier
Rvalue Reference Parameters
Arguments to main( )
Accepting a Variable Number of Function Arguments

Returning Values from a Function
Returning a Pointer
A Cast-Iron Rule for Returning Addresses
Returning a Reference
A Teflon-Coated Rule: Returning References
Static Variables in a Function

Recursive Function Calls

191
191
191
193
193
194
194
194

198
199
200
202
204
206

208
210
212
214

216
216
218
219
222
222

224

Using Recursion

227

Summary

227

xxi

www.it-ebooks.info
ftoc.indd xxi

17/09/12 10:42 AM



CONTENTS

CHAPTER 6: MORE ABOUT PROGRAM STRUCTURE

Pointers to Functions

231

231

Declaring Pointers to Functions
A Pointer to a Function as an Argument
Arrays of Pointers to Functions

Initializing Function Parameters
Exceptions
Throwing Exceptions
Catching Exceptions
Rethrowing Exceptions
Exception Handling in the MFC

Handling Memory Allocation Errors
Function Overloading
What Is Function Overloading?
Reference Types and Overload Selection
When to Overload Functions

Function Templates

232

235
237

238
239
241
242
244
244

245
247
247
250
251

251

Using a Function Template

251

Using the decltype Operator
An Example Using Functions

254
256

Implementing a Calculator
Analyzing the Problem

Eliminating Blanks from a String
How the Function Functions
Evaluating an Expression
How the Function Functions
Getting the Value of a Term
How the Function Functions
Analyzing a Number
How the Function Functions
Putting the Program Together
How the Function Functions
Extending the Program
How the Function Functions
Extracting a Substring
How the Function Functions
Running the Modified Program

Summary

257
257
260
260
260
262
263
264
264
266
268
269

269
271
271
273
273

274

xxii

www.it-ebooks.info
ftoc.indd xxii

17/09/12 10:42 AM


CONTENTS

CHAPTER 7: DEFINING YOUR OWN DATA TYPES

The struct in C++

277

277

What Is a struct?
Defining a struct
Initializing a struct
Accessing the Members of a struct

IntelliSense Assistance with Structures
The struct RECT
Using Pointers with a struct
Accessing Structure Members through a Pointer
The Indirect Member Selection Operator

Types, Objects, Classes, and Instances

278
278
279
279
283
285
285
286
287

287

First Class
Operations on Classes
Terminology

289
289
290

Understanding Classes


290

Defining a Class
Access Control in a Class
Declaring Objects of a Class
Accessing the Data Members of a Class
Member Functions of a Class
Positioning a Member Function Definition
Inline Functions

Class Constructors

291
291
291
292
294
296
297

298

What Is a Constructor?
The Default Constructor
Default Parameter Values
Using an Initialization List in a Constructor
Making a Constructor Explicit

Private Members of a Class


298
300
303
305
306

307

Accessing private Class Members
The friend Functions of a Class
Placing friend Function Definitions Inside the Class
The Default Copy Constructor

The Pointer this
const Objects

310
310
312
313

314
317

const Member Functions of a Class
Member Function Definitions Outside the Class

Arrays of Objects

318

319

320

xxiii

www.it-ebooks.info
ftoc.indd xxiii

17/09/12 10:42 AM


×