Tải bản đầy đủ (.pdf) (1,276 trang)

1750 beginning visual c++ 2010

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 (38.76 MB, 1,276 trang )

Join the discussion @ p2p.wrox.com

Wrox Programmer to Programmer™

Ivor Horton’s

Beginning

Visual C++ 2010
®

Ivor Horton
www.it-ebooks.info


Programmer to Programmer™

Get more out of
wrox.com
Interact

Join the Community

Take an active role online by participating in our
P2P forums @ p2p.wrox.com

Sign up for our free monthly newsletter at
newsletter.wrox.com

Wrox Online Library


Browse

Hundreds of our books are available online
through Books24x7.com

Ready for more Wrox? We have books and
e-books available on .NET, SQL Server, Java,
XML, Visual Basic, C#/ C++, and much more!

Wrox Blox
Download short informational pieces and code
to keep you up to date and out of trouble!

Contact Us.
We always like to get feedback from our readers. Have a book idea?
Need community support? Let us know by e-mailing
www.it-ebooks.info


IVOR HORTON’S
BEGINNING VISUAL C++® 2010
INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxiii
CHAPTER 1

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

CHAPTER 2

Data, Variables, and Calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35


CHAPTER 3

Decisions and Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

CHAPTER 4

Arrays, Strings, and Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167

CHAPTER 5

Introducing Structure into Your Programs . . . . . . . . . . . . . . . . . . . . . . . . 251

CHAPTER 6

More about Program Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295

CHAPTER 7

Defining Your Own Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353

CHAPTER 8

More on Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435

CHAPTER 9

Class Inheritance and Virtual Functions . . . . . . . . . . . . . . . . . . . . . . . . . 549

CHAPTER 10


The Standard Template Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645

CHAPTER 11

Debugging Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 755

CHAPTER 12

Windows Programming Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 807

CHAPTER 13

Programming for Multiple Cores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 843

CHAPTER 14

Windows Programming with the Microsoft Foundation Classes . . . . . 875

CHAPTER 15

Working with Menus and Toolbars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 903

CHAPTER 16

Drawing in a Window. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 945

CHAPTER 17

Creating the Document and Improving the View . . . . . . . . . . . . . . . . . 1009


CHAPTER 18

Working with Dialogs and Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1059

CHAPTER 19

Storing and Printing Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1123

CHAPTER 20

Writing Your Own DLLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1175

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1193

www.it-ebooks.info


www.it-ebooks.info


IVOR HORTON’S
BEGINNING

Visual C++® 2010

www.it-ebooks.info


www.it-ebooks.info



IVOR HORTON’S
BEGINNING

Visual C++® 2010
Ivor Horton

www.it-ebooks.info


Ivor Horton’s Beginning Visual C++® 2010
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2010 by Ivor Horton
Published by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-0-470-50088-0
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 also publishes its books in a variety of electronic formats. Some content that appears in print may not be available
in electronic books.
Library of Congress Control Number: 2010921242
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 in the United States and/or other countries. All other trademarks are the property of their respective owners.
Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.

www.it-ebooks.info


This book is for Edward Gilbey, who arrived in
September 2009 and has been a joy to have around ever since.

www.it-ebooks.info


www.it-ebooks.info



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 scientists and
engineers primarily to do likewise. He has been writing books on programming for more than 15
years now, 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


www.it-ebooks.info


ABOUT THE TECHNICAL EDITOR

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


Leuven, Belgium, with a degree in “Burgerlijk ingenieur in de computer wetenschappen” (equivalent
to Master of Science in Engineering in Computer Science). After that, he received the cum laude
degree of Master in Artificial Intelligence at the same university, started working for a big software
consultancy company (Ordina: ). His main expertise is C/C++, 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 24x7 on Linux platforms, and in developing critical
2G and 3G software running on Solaris for big telecom operators.
In April of the years 2007, 2008, and 2009 he received the Microsoft MVP (Most Valuable
Professional) award for his Visual C++ expertise.
Marc is an active member on the CodeGuru forum (as Marc G) and also wrote some articles
and FAQ entries for CodeGuru. He 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


www.it-ebooks.info


CREDITS

EXECUTIVE EDITOR

VICE PRESIDENT AND EXECUTIVE GROUP
PUBLISHER

Robert Elliott

Richard Swadley

PROJECT EDITOR

John Sleeva

VICE PRESIDENT AND EXECUTIVE PUBLISHER

Barry Pruett
TECHNICAL EDITOR

Marc Gregoire

ASSOCIATE PUBLISHER

Jim Minatel
PRODUCTION EDITOR

Eric Charbonneau

PROJECT COORDINATOR, COVER

Lynsey Stanford
COPY EDITOR

Sadie Kleinman

PROOFREADERS

Maraya Cornell and Paul Sagan, Word One
EDITORIAL DIRECTOR


Robyn B. Siesky

INDEXER

Johnna VanHoose Dinse
EDITORIAL MANAGER

Mary Beth Wakefield

COVER DESIGNER

Michael E. Trent
MARKETING MANAGER

Ashley Zurcher

COVER IMAGE

©istockphoto
PRODUCTION MANAGER

Tim Tate

www.it-ebooks.info


www.it-ebooks.info


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 an
outstanding job of reviewing the text and checking out all the code fragments and examples in the
book. His many constructive comments and suggestions for better ways of presenting the material
has undoubtedly made the book a much better tutorial.
As always, the love and support of my wife, Eve, has been fundamental to making it possible for me
to write this book alongside my other activities. She provides for my every need and remains patient
and cheerful in spite of the effect that my self-imposed workload has on family life.

www.it-ebooks.info


www.it-ebooks.info


CONTENTS

INTRODUCTION

xxxiii

CHAPTER 1: PROGRAMMING WITH VISUAL C++ 2010

1

The .NET Framework

The Common Language Runtime
Writing C++ Applications
Learning Windows Programming

2
2
3
5

Learning C++
The C++ Standards
Attributes
Console Applications
Windows Programming Concepts

5
5
6
6
7

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

9
9
10

10
10

Using the IDE

10

Toolbar Options
Dockable Toolbars
Documentation
Projects and Solutions
Setting Options in Visual C++ 2010
Creating and Executing Windows Applications
Creating a Windows Forms Application

Summary

12
12
13
13
27
28
31

32

CHAPTER 2: DATA, VARIABLES, AND CALCULATIONS

The Structure of a C++ Program

The main() Function
Program Statements
Whitespace
Statement Blocks
Automatically Generated Console Programs

www.it-ebooks.info

35

36
44
44
46
47
47


CONTENTS

Defining Variables

49

Naming Variables
Declaring Variables
Initial Values for Variables

Fundamental Data Types


49
50
51

52

Integer Variables
Character Data Types
Integer Type Modifiers
The Boolean Type
Floating-Point Types
Literals
Defining Synonyms for Data Types
Variables with Specific Sets of Values

52
53
55
56
56
58
59
59

Basic Input/Output Operations

61

Input from the Keyboard
Output to the Command Line

Formatting the Output
Escape Sequences

61
62
63
64

Calculating in C++

66

The Assignment Statement
Arithmetic Operations
Calculating a Remainder
Modifying a Variable
The Increment and Decrement Operators
The Sequence of Calculation

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

The Auto Keyword
Discovering Types
The Bitwise Operators

66
67

72
73
74
76

78
79
79
80

81
81
82

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

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

xviii

www.it-ebooks.info

82

84
85
86
86

88
89
89
92


CONTENTS

Global Variables
Static Variables

92
96

Namespaces

96

Declaring a Namespace
Multiple Namespaces

97
99

C++/CLI Programming


100

C++/CLI Specific: Fundamental Data Types
C++/CLI Output to the Command Line
C++/CLI Specific — Formatting the Output
C++/CLI Input from the Keyboard
Using safe_cast
C++/CLI Enumerations

Discovering C++/CLI Types
Summary

101
105
106
109
110
111

116
116

CHAPTER 3: DECISIONS AND LOOPS

Comparing Values

121

121


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

Repeating a Block of Statements
What Is a Loop?
Variations on the for Loop
The while Loop
The do-while Loop
Nested Loops

123
124
128
130
133
135
139

139
139
142
150
152
154


C++/CLI Programming

157

The for each Loop

161

Summary

163

CHAPTER 4: ARRAYS, STRINGS, AND POINTERS

Handling Multiple Data Values of the Same Type
Arrays
Declaring Arrays
Initializing Arrays
Character Arrays and String Handling
Multidimensional Arrays

167

168
168
169
172
174
177

xix

www.it-ebooks.info


CONTENTS

Indirect Data Access

180

What Is a Pointer?
Declaring Pointers
Using Pointers
Initializing Pointers
The sizeof Operator
Constant Pointers and Pointers to Constants
Pointers and 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

181
181
182

183
190
192
194

201
201
202
203
206

206

What Is a Reference?
Declaring and Initializing Lvalue References
Defining and Initializing Rvalue References

Native C++ 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

C++/CLI Programming

207
207
208


208
209
210
211
212
213

215

Tracking Handles
CLR Arrays
Strings
Tracking References
Interior Pointers

216
217
233
244
244

Summary

247

CHAPTER 5: INTRODUCING STRUCTURE INTO YOUR PROGRAMS

Understanding Functions
Why Do You Need Functions?
Structure of a Function

Using a Function

Passing Arguments to a Function
The Pass-by-value Mechanism
Pointers as Arguments to a Function
Passing Arrays to a Function
References as Arguments to a Function

xx

www.it-ebooks.info

251

252
253
253
256

259
260
262
263
267


CONTENTS

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
Returning a Reference
Static Variables in a Function

Recursive Function Calls

270
271
273
275

277
277
280
283

285

Using Recursion

288

C++/CLI Programming

289


Functions Accepting a Variable Number of Arguments
Arguments to main()

Summary

289
290

292

CHAPTER 6: MORE ABOUT PROGRAM STRUCTURE

Pointers to Functions

295

295

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
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

296
299
301

302
303
305
306
307

308
310
310
313
313

314

Using a Function Template

314

Using the decltype Operator
An Example Using Functions


317
318

Implementing a Calculator
Eliminating Blanks from a String
Evaluating an Expression
Getting the Value of a Term
Analyzing a Number
Putting the Program Together
Extending the Program

319
322
322
325
326
330
331

xxi

www.it-ebooks.info


CONTENTS

Extracting a Substring
Running the Modified Program


C++/CLI Programming

333
336

336

Understanding Generic Functions
A Calculator Program for the CLR

Summary

337
343

349

CHAPTER 7: DEFINING YOUR OWN DATA TYPES

The struct in C++

353

354

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

Data Types, Objects, Classes, and Instances

354
354
355
355
359
360
361

363

First Class
Operations on Classes
Terminology

364
364
365

Understanding Classes

366

Defining 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

366
367
367
370
372
372

374

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

Private Members of a Class
Accessing private Class Members
The friend Functions of a Class
The Default Copy Constructor

The Pointer this
const Objects

374

376
378
381
381

382
385
386
388

390
393

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

xxii

www.it-ebooks.info

393
394


CONTENTS

Arrays of Objects
Static Members of a Class

395

397

Static Data Members
Static Function Members of a Class

Pointers and References to Class Objects
Pointers to Objects
References to Class Objects

397
401

401
401
404

C++/CLI Programming

406

Defining Value Class Types
Defining Reference Class Types
Defining a Copy Constructor for a Reference Class Type
Class Properties
initonly Fields
Static Constructors

Summary

407

412
415
416
429
431

432

CHAPTER 8: MORE ON CLASSES

Class Destructors

435

435

What Is a Destructor?
The Default Destructor
Destructors and Dynamic Memory Allocation

Implementing a Copy Constructor
Sharing Memory Between Variables
Defining Unions
Anonymous Unions
Unions in Classes and Structures

Operator Overloading

436
436

438

442
444
444
446
446

446

Implementing an Overloaded Operator
Implementing Full Support for a Comparison Operator
Overloading the Assignment Operator
Overloading the Addition Operator
Overloading the Increment and Decrement Operators
Overloading the Function Call Operator

The Object Copying Problem
Avoiding Unnecessary Copy Operations
Applying Rvalue Reference Parameters
Named Objects are Lvalues

Class Templates

447
450
454
459
463
465


466
466
470
472

477

Defining a Class Template
Creating Objects from a Class Template
Class Templates with Multiple Parameters
Templates for Function Objects

478
481
483
486
xxiii

www.it-ebooks.info


×