Đây là quyển sách tiếng anh về lĩnh vực công nghệ thông tin cho sinh viên và những ai có đam mê. Quyển sách này trình về lý thuyết ,phương pháp lập trình cho ngôn ngữ C và C++.
Trang 1<iterator> Def ines a number of classes, class t emplat es, and f unct ion t emplat es used f or t he declarat ion and
manipulat ion of it erat ors—it erat ors and it erat or support
LANGUAGE SUPPORT
<cfloat> Includes t he St andard C header <float.h> w it hin t he std namespace, providing C-st yle f loat ing-point limit
macros.
<ciso646> Includes t he St andard C header <iso646.h> w it hin t he std namespace.
<climits> Includes t he St andard C header <limits.h> w it hin t he std namespace, providing C-st yle numeric scalar-limit
macros.
<csetjmp> Includes t he St andard C header <setjmp.h> w it hin t he std namespace, providing C-st yle st ack unw inding.
<csignal> Includes t he St andard C header <signal.h> w it hin t he std namespace, providing C-st yle signal handling.
<cstdarg> Includes t he St andard C header <stdarg.h> w it hin t he std namespace, providing variable-lengt h f unct ion
argument list s.
<cstddef> Includes t he St andard C header <stddef.h> w it hin t he std namespace, providing C library language support
<exception> Def ines several t ypes and f unct ions relat ed t o except ion handling.
<limits> Def ines t he class t emplat e numeric_limits , w hose specializat ions describe arit hmet ic propert ies of scalar
dat a t ypes.
LOCALIZATION
<clocale> Includes t he St andard C header <locale.h> w it hin t he std namespace, represent ing cult ural diff erences
C-st yle.
<locale> Def ines many class t emplat es and f unct ion t emplat es t hat encapsulat e and manipulat e locales, w hich repre
sent cult ural diff erences.
NUM ERICS
<cmath> Includes t he St andard C header <math.h> w it hin t he std namespace, providing st andard mat h f unct ions.
<complex> Provides a class t emplat e describing an object t hat st ores bot h t he real part and t he imaginary part of a
complex number.
<cstdlib> Includes t he St andard C header <stdlib.h> w it hin t he std namespace, providing pseudo-random numbers.
<numeric> Def ines several f unct ion t emplat es usef ul f or comput ing numeric values—generalized numeric operat ions.
<valarray> Def ines t he class t emplat e valarray along w it h many support ing t emplat e classes and f unct ions, providing
numeric vect ors and operat ions.
STRINGS
<cctype> Includes t he St andard C header <ctype.h> w it hin t he std namespace—charact er classsif icat ion.
<cstdlib> Includes t he St andard C header <stdlib.h> w it hin t he std namespace, providing C-st yle st ring and charact er
<cwctype> Includes t he St andard C header <wctype.h> w it hin t he std namespace, providing C-st yle w ide charact er
st ring f unct ions.
Def ines t he cont ainer t emplat e class and various support ing t emplat es—a st ring of T.
Trang 3How -To
C++
Jan Walter Danny Kalev
M ichael J Tobler Paul Snaith Andrei Kossoroukov
Scott Roberts
A Division of Macmillan Computer Publishing
201 West 103rd St., Indianapolis, Indiana, 46290 USA
Trang 4Copyright 1999 by Sam s Publishing
All rights reserved No part of this book shall be reproduced,
stored in a retrieval system, or transmitted by any means,
elec-tronic, mechanical, photocopying, recording, or otherwise,
without written permission from the publisher No patent liability
is assumed with respect to the use of the information contained
herein Although every precaution has been taken in the
prepara-tion of this book, the publisher and author assume no
responsi-bility for errors or omissions Neither is any liaresponsi-bility assumed for
damages resulting from the use of the information contained
herein.
International Standard Book Number: 1-57169-159-6
Library of Congress Catalog Card Number: 98-86976
Printed in the United States of America
First Printing: January, 1999
02 01 00 99 4 3 2 1
Tradem arks
All terms mentioned in this book that are known to be
trade-marks or service trade-marks have been appropriately capitalized Sams
Publishing cannot attest to the accuracy of this information Use
of a term in this book should not be regarded as affecting the
validity of any trademark or service mark.
Warning and Disclaim er
Every effort has been made to make this book as complete and as
accurate as possible, but no warranty or fitness is implied The
information provided is on an “as is” basis The authors and the
publisher shall have neither liability or responsibility to any
person or entity with respect to any loss or damages arising from
the information contained in this book or from the use of the CD
or programs accompanying it.
S OFTWARE D EVELOPM ENT
Trang 5C O N T E N T S A T A G L A N C E
PRACTICE 51
CHAPTER 4: STRUCTURES VERSUS CLASSES 105
CHAPTER 6: TEM PLATE CLASSES 217
CHAPTER 10: C-STYLE ERROR HANDLING 371
CHAPTER 11: EXCEPTION HANDLING IN C++ 407
Trang 6INTRODUCTION 1
PA RT I
La n g u a g e To p i cs
C H A P T E R 1
A QUICK INTRODUCTION TO THE LANGUAGE 9
1.1 Write the simplest C++ program without knowing the language 12
1.2 Create a program to perform calculations 17
1.3 Use the various loop statements that are available in C++ 21
1.4 Create a program that uses one or more functions 25
1.5 Use the derived data types such as arrays and pointers 29
1.6 Create data when the program is running 37
1.7 Create a program to perform error handling, specifically exception handling 41
C H A P T E R 2 OBJECT ORIENTATION—THEORY AND PRACTICE 53
2.1 Understand the object-oriented paradigm 55
2.2 Learn the concept of inheritance so that I can apply it programmatically 57
2.3 Learn the concept of encapsulation 62
2.4 Learn the concept of polymorphism 64
C H A P T E R 3 OBJECT ORIENTATION—C++ SPECIFICS 71
3.1 Create a simple class in C++ 72
3.2 Implement the use of inheritance in C++ 80
3.3 Apply the use of encapsulation in a C++ program 87
3.4 Implement polymorphism in C++ 91
3.5 Implement static members of a class 97
PA RT I I D a t a St r u ct u re s C H A P T E R 4 STRUCTURES VERSUS CLASSES 107
4.1 Create my own data type 110
4.2 Hide my data from external programs 118
4.3 Use encapsulation? What steps are required to encapsulate data? 129
Trang 74.4 Create my own operators 134
4.5 Overload relational and equality operators 139
4.6 Provide access to encapsulated data to certain classes 144
4.7 Maintain global data in my program 148
4.8 Know when I should use structures and when I should use classes 151
C H A P T E R 5 COM M ON M ISTAKES M ADE W ITH CLASSES 159
5.1 Know when to take an object-oriented approach or a procedural approach 162
5.2 Use and access a class’s data members 169
5.3 Use the scope resolution operator 175
5.4 Use dot notation to access the member functions of an object 181
5.5 Know which constructor to use when there are several to choose from 186
5.6 Implement function overloading 191
5.7 Correctly make use of inheritance 194
5.8 Pass parameters back through the C++ inheritance mechanism to parent classes 200
5.9 Distinguish between virtual classes and nonvirtual classes? How do I know when to use virtual classes and what does the word virtual mean in C++? 206
C H A P T E R 6 TEM PLATE CLASSES 219
6.1 Create a template class to represent any simple data type and understand how to use the template in a working C++ program 221
6.2 Create a template class to represent any simple data type and extend it to read in data to a variable of any data type 225
6.3 Create a template class to represent a compound data type and understand how to use the template in a working C++ program 228
6.4 Write a template class that has two undefined data types that can be resolved at a later time 233
6.5 Use a template class to handle a structure 238
C H A P T E R 7 THE STANDARD TEM PLATE LIBRARY’S CONTAINER CLASSES 247
7.1 Create a container object that automatically grows or shrinks as needed 250
7.2 Read a single element of a container 254
7.3 Modify a single element of a container 257
7.4 Use a generic LIFO data model 261
7.5 Prevent automatic reallocation of a container 268
7.6 Traverse through a container’s elements 273
7.7 Implement a queue data model 278
Trang 8PA RT I I I
A l g o r i t h m s
C H A P T E R 8
THE STANDARD C LIBRARY’S INCLUDED ALGORITHM S 287
8.1 Sort an array 289
8.2 Find an element in an array 298
8.3 Locate an element in a nonsorted array 302
8.4 Choose between _lfindand _lsearch 305
8.5 Generate a sequence of random numbers 309
C H A P T E R 9 THE STANDARD TEM PLATE LIBRARY’S INCLUDED ALGORITHM S 315
9.1 Create classes for sequential containers 320
9.2 Use predicates with sequence operations 328
9.3 Repeat an action with all elements in a container range 333
9.4 Compare two sequences 337
9.5 Search for a sequence of values in a container 341
9.6 Accumulate all container elements and create a sequence of accumulated sums 345
9.7 Sort elements in a container using different sorting indexes 351
9.8 Change the order of the container elements 362
PA RT I V Er ro r Ha n d l i n g C H A P T E R 1 0 C-STYLE ERROR HANDLING 373
10.1 Handle runtime errors in my programs 376
10.2 Use the standard C library functions perrorand strerrorand the predefined C macros to report runtime errors in my programs 381
10.3 Use assertto catch errors in my code when running in debug mode 385
10.4 Use raiseand signalto indicate errors in my programs 387
10.5 Use abortto terminate my application if a serious error occurs 391
10.6 Use exitand atexittogether to perform some action when my program terminates normally 393
10.7 Detect errors that occur when reading from or writing to a file using the file functions provided with the Standard C Library 395
10.8 Use setjmpand longjmpto maintain state when handling errors 397
10.9 Use a C++ class to handle runtime errors in a more maintainable fashion 400
Trang 9CO N T EN T S
ix
C H A P T E R 1 1
EXCEPTION HANDLING IN C++ 409
11.1 Utilize the exception handling mechanism to process potential error conditions 411
11.2 Use the various catchconstructs such as multiple catchclauses, catchordering, and the rethrowing of exceptions 419
11.3 Implement and use an exception class 425
11.4 Specify exceptions that a function will throw 430
11.5 Handle exceptions that are not caught or not expected 434
PA RT V M e m o r y M a n a g e m e n t C H A P T E R 1 2 NEW AND DELETE VERSUS MALLOC() AND FREE() 443
12.1 Use newand deletewith the C malloc()and free()routines 445
12.2 Use other C mem routines on objects allocated with new 446
12.3 Find out how much memory my structures and classes really take 447
12.4 Prevent memory leaks caused by not using delete[]to delete arrays 450
12.5 Override the newor deleteoperators for my classes 451
12.6 Overload the newand deletefunctions for arrays 455
C H A P T E R 1 3 M EM ORY M ANAGEM ENT TECHNIQUES USING CLASSES 473
13.1 Make a simple class to clean up dynamically allocated memory automatically 475
13.2 Make a class that automatically cleans up objects allocated with new 479
13.3 Make an object that deallocates itself when there is no more code referencing it 483
PA RT V I I /O C H A P T E R 1 4 UNDERSTANDING THE I/ O STREAM S LIBRARY 499
14.1 Use the C Standard I/O Library with the C++ I/O streams library 500
14.2 Make my own classes compatible with cinand cout 503
14.3 Perform complex formatting with coutor another ostreamobject 504
14.4 Make my own stream manipulators 515
Trang 10C H A P T E R 1 5
FILE I/ O 525
15.1 Open a file stream 526
15.2 Continually read data until the end of file 529
15.3 Handle stream errors 532
15.4 Read and write binary files 536
15.5 Read from or write to different positions in a file 542
PA RT V I I A p p e n d i x e s A P P E N D I X A NAM ESPACES 549
The Rationale Behind Namespaces 550
A Brief Historical Background 550
Large-Scale Projects Are Susceptible to Name Clashes 550
Properties of Namespaces 551
A Fully Qualified Name 551
A using-Declaration and a using-Directive 551
Namespaces Are Open 552
Namespace Aliases 553
Koenig Lookup 554
Namespaces Do Not Incur Additional Overhead 554
The Interaction of Namespaces with Other Language Features 554
::Operator Should Not Be Used to Designate a Global Function 555
Turning an External Function into a File-Local Function 555
Standard Headers Names 556
Restrictions on Namespaces 557
Namespace stdMay Not Be Modified 557
User-Defined newand deleteCannot Be Declared in a Namespace 557
Comments 558
A P P E N D I X B RUNTIM E TYPE INFORM ATION 559
Static Binding 559
Dynamic Binding 560
Historical Background 563
RTTI Constituents 563
Comments 568
INDEX 569
Trang 11A B O U T T H E A U T H O R S
Jan Walter is a freelance computer consultant living around Vancouver, B.C.,
Canada He spends most of his time doing network design and implementation,
but “would rather be coding.” Jan has fulfilled programming contracts with
several large companies in the area, mostly using C++ Code optimization and
performance tuning are a distinct area of interest, as is compiler technology The
latter came about after spending a lot of time hunting down bugs introduced by
parser problems in Borland C++ in one of his projects
This is his second project with Macmillan Computer Publishing The first was
as contributing author to Que’s Using Linux, by Bill Ball, 1998.
Jan Walter can be reached at jwalter@rogers.wave.ca
Danny Kalev is a certified system analyst and software engineer with 10 years
of experience, specializing in C++ and object-oriented analysis and design He
is now finishing his M.A degree in applied linguistics at the University of Tel
Aviv, Israel His research focuses on speech recognition algorithms He is a hi-fi
enthusiast and likes all kinds of music He is also interested in natural
languages and philology
His technical interests involve generic programming, networking, compiler
technology, artificial intelligence, and embedded systems He has contributed
several articles to C++ magazines and Web publishers He is also a member of
the ANSI C++ standardization committee He can be reached at
Michael J Tobler is a senior technical specialist with BSI Consulting in
Houston, Texas He has more than 16 years experience working on software
development projects, specializing in architecting, designing, and developing
multitier systems using C++ and Java He is currently the president of the
Houston Java Users Group Michael is an advocate and practitioner of the
Unified Modeling process from Rational and a proponent of patterns and
pattern languages He is a contributing author for C++ Unleashed He has
discovered that skydiving is a very addicting sport Michael can be reached at
mtobler@ibm.net
Paul Snaith works in the I.T industry in the UK He is currently a project
leader in software development for a well-known British airline dealing mainly
with Web development and electronic commerce Previously, he spent several
years lecturing in modern computer languages such as C++, Java, VB, and
Delphi In the far distant past (only a few years ago but it seems much longer),
Paul was involved in the rock music industry as a musician and played with the
wonders of electronic computer generation of his work Paul has just finished
another book called The Complete Idiot’s Guide to C++ and is planning other such
Trang 12in 1985 Working with computers for the last 25 years, he has developed cial intelligence systems, financial software, and distributed messaging systems.
artifi-He is an author of more than 30 scientific and technical articles, papers, andbooks Currently he works for I.T Systems, Inc.(Vancouver, B.C., Canada) as asenior software consultant and specializes in the development of Internet-basedsystems with distributed data
Scott Roberts works as a developer support engineer on the Internet Client
Development team at Microsoft He assists developers who are using Visual C++and COM to create Internet applications Scott has been a developer for 9 yearsand has worked at a number of companies on a wide range of products, fromback-end communications systems to end-user software applications Scott hasbeen a frequent contributor to many technical publications, including MicrosoftInteractive Developer and Microsoft Systems Journal In addition, he hasspoken at many technical conferences in the United States and Europe Scottcan be reached at scottrobe@hotmail.com
xii
Trang 13D E D I C A T I O N
I dedicate this book to my grandparents In their time, people went through so much, and many gave their
lives to let us have what we have now It is easy for us today to look back 60 years and say, “Times were tough
then,” but we have little comprehension of what actually went on
“Lest we forget” is an apt phrase to take to heart.
—Jan Walter
A C K N O W L E D G M E N T S
I do also need to thank the staff at Macmillan Computer Publishing for their
seemingly infinite patience Many thanks for encouragement go to Michelle
Newcomb, and thanks, Bryan, for your insightful feedback
—Jan Walter
Trang 14As the reader of this book, you are our most important critic and commentator.
We value your opinion and want to know what we’re doing right, what wecould do better, what areas you’d like to see us publish in, and any other words
of wisdom you’re willing to pass our way
As the executive editor for the Advanced Programming and Distributed
Architectures team at Macmillan Computer Publishing, I welcome your
comments You can fax, email, or write me directly to let me know what youdid or didn’t like about this book—as well as what we can do to make ourbooks stronger
Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message.
When you write, please be sure to include this book’s title and author as well asyour name and phone or fax number I will carefully review your commentsand share them with the author and editors who worked on the book
Email: programming@mcp.com
Mail: Tracy Dunkelberger
Executive EditorAdvanced Programming and Distributed Architectures TeamMacmillan Computer Publishing
201 West 103rd StreetIndianapolis, IN 46290 USA
Trang 15I N T R O D U C T I O N
Despite the development of several new languages over the past five years, C++has held its own in the development world Originally developed at AT&T BellLaboratories by Bjarne Stoustrup, the language has evolved to encompass evermore object-oriented concepts
With the latest ANSI revision of C++, version 3, the language gets some tuning in memory management, solid exception support, and new typecastingoperators The biggest improvement, however, was the introduction of the
fine-Standard Template Library (STL), which provides a standard set of containerclasses and the means to work with them Before this, most compiler vendorsincluded their own container classes and other objects in their libraries, posing
an impediment to porting code from one platform to another where the samevendor’s compiler was not supported
What makes C++ so useful? Some people say that its C language nings are great for getting as close to the hardware as possible without usingassembler code Developers find that the strong typing by the C++ languagehelps reduce the number of bugs in programs Some people use C++ as “just abetter C,” but the point is missed then: The object-oriented programming(OOP) style makes it easier to translate from the problem language and problemworld to the solution language
underpin-The great misconception of many people is that object-oriented ming produces slower code This is not necessarily so If a problem can be put
program-so that a human mind can understand it better, it is likely that this mind canproduce a better solution Algorithms, and their efficiency, have a much greaterimpact on program performance than the language does C++ is only marginallyslower than C code overall, and this makes it one of the fastest executinglanguages for object-oriented programming
This book is intended to be an eye-opener for C++ programmers I admitfreely that I learn the most from reading other peoples’ code, as I learn theirapproaches to problems It’s easy to get stuck in one way of doing things, andthis is dangerous with any creative exercise Computer programming is noexception What’s written in this book is not gospel, but yet another approachthat can be added to your arsenal
Trang 16The Waite Group’s C++ How-Tois divided into 15 chapters, each of which
covers a specific feature of the C++ programming language:
• Chapter 1, “A Quick Introduction to the Language”—Before diving into the
“deep end” of C++ programming, this chapter provides a gentle introductioninto the basic concepts of the language Loops, calculations, and error handlingare all covered here for the beginning C++ programmer
• Chapter 2, “Object Orientation—Theory and Practice”—To fully make use ofthe C++ language, object-oriented programming must be understood Many C,Pascal, and COBOL programmers are assigned to C++ projects and never takethe time—or get the opportunity—to fully learn the benefits of OOP Withoutfocusing on the specific syntax used in C++, this chapter covers the basicobject-oriented concepts required to become a great C++ programmer
• Chapter 3, “Object Orientation—C++ Specifics”—After learning or reviewingthe basic concepts of object-oriented programming in Chapter 2, you will learnhow these concepts are specifically applied to C++ in this chapter The basictenets of OOP—inheritance, polymorphism, and encapsulation—are all coveredhere as well as the fundamental C++ unit: the class
• Chapter 4, “Structures Versus Classes”—C++ provides two primary devices thatcan be used to contain data: structures and classes Although the two datastructures can be identical, classes are much more powerful because they fullysupport the primary OOP constructs This chapter compares and contraststhese two data types and provide numerous examples of their use
• Chapter 5, “Common Mistakes Made with Classes”—Because of the tremendousdifference between traditional structured programming and object-orientedprogramming, many beginning-to-intermediate–level programmers makeseveral common mistakes This chapter introduces these mistakes, explains whythey are mistakes, and offers solutions to them
• Chapter 6, “Template Classes”—The template class is a mechanism that enablesyou to write a single solution to a problem that can satisfy all data types Theactual data type required can be specified later, and the template class can then
be used for a wide range of data types, all using the same C++ template Thischapter introduces the template class, or templates as they are commonlyknown
• Chapter 7, “The Standard Template Library’s Container Classes”—In thischapter, you will explore the following containers of the Standard TemplateLibrary: vector, string, stack, list, and queue I also discuss iterators and theirrole in the STL framework Finally, you will survey some other containers aswell as “almost container” classes of the Standard Library
2
Trang 17• Chapter 8, “The Standard C Library’s Included Algorithms”—In this chapter, I
survey the algorithms of the Standard C Library These algorithms enable you tosort an array and find an element in it In addition, I discuss the random
number generation functions of the Standard C Library
• Chapter 9, “The Standard Template Library’s Included Algorithms”—STL
algo-rithms are represented by template functions and provide copying, searching,
sorting, and merging functions, as well as other operations on data Algorithmsare not member functions; they are separate from the container classes You willexamine a number of these algorithms in this chapter I give examples, where
possible, showing their use in typical situations
• Chapter 10, “C-Style Error Handling”—This chapter covers different
error-handling methods that work in C and C++ programs and some methods that
don’t work well in C++ programs Although this is a C++ book, I discuss C-typeerror-handling techniques so that you will know what you are dealing with if
you run into them in older C and C++ programs
• Chapter 11, “Exception Handling in C++”—The exception-handling mechanismfurnished by the standard provides a common and standard interface for
handling program anomalies Without exception handling, error handling is
performed using return values from functions and global status variables Eachdeveloper has his or her own style of handling errors, leading to inconsistency
among applications and library packages In this chapter, you will see various
ways to apply the exception-handling mechanisms
• Chapter 12, “newand deleteVersus malloc()and free()”—This chapter
compares and contrasts the C++ newand deleteoperators and the C functions
malloc()and free(), and it covers their place in C++ memory management
You must understand memory management using C and C++ techniques
because of the existence of legacy code and because many existing libraries usethe older C language techniques
• Chapter 13, “Memory Management Techniques Using Classes”—Whereas
C-style memory management basically requires the programmer to free
variables that have been created, C++-style memory management is much morepowerful, although a bit more challenging This chapter focuses on many
advanced memory management techniques that you can use to improve the
reliability and performance of your applications
I N T RO D U CT I O N
3
Trang 18• Chapter 14, “Understanding the I/O Streams Library”—So many programmersseem to have difficulty with the C++ I/O Streams library that it is quite common
to see C++ code still using the old C stdiofunctions to handle program I/O.Although some programmers might consider this approach practical, or evensuperior, the C stdiolibrary does not do much to help good programmingpractice or catch oversights made by the programmer This chapter introducesthe basic concepts required to use the Streams library and shows why it is apreferred solution to the standard C method
• Chapter 15, “File I/O”—This chapter covers IOStreamswith a focus on filestreams Examples are provided that demonstrate how to seek through files,read/write binary files, and manage file I/O errors
This book also includes two appendixes, one on namespaces and another onruntime type information (RTTI)
WHO IS THIS BOOK INTENDED FOR?
The Waite Group’s C++ How-Tois designed for C++ programmers of all skill
levels, from beginning to advanced However, I anticipate that readers who pick
up this book already have a solid understanding of C++ programming and arelooking for “just the answers” to specific programming questions This is also agreat supplemental resource for new C++ programmers searching for informa-
tion and instruction that goes beyond a typical tutorial
4
Trang 19P A R T I
LANGUAGE TOPICS
Trang 21C H A P T E R 1
A QUICK INTRODUCTION TO THE LANGUAGE
Trang 231.2 Creat e a program t o perf orm calculat ions?
1.3 Use t he various loop st at em ent s t hat are available
in C++?
1.4 Creat e a program t hat uses one or m ore f unct ions? 1.5 Use t he derived dat a t ypes such as arrays and
point ers?
1.6 Creat e dat a w hen t he program is running?
1.7 Creat e a program t o perf orm error handling,
specif ically except ion handling?
Trang 24The C++ programming language is one of the most significant languages toemerge in the past twenty years The C++ language is also the most popularobject-oriented language in use today I will examine the object-orientedfeatures of C++ beginning with Chapter 3, “Object-Orientation—C++ Specifics.”Everything from word processors to spreadsheets, graphics applications, andoperating systems is written in the C++ language, and a majority of all custom-written solutions are implemented in C++ as well Despite this, manyprogrammers have yet to make the switch to C++.
This chapter introduces you to the C++ programming language Theintended audience for this chapter is programmers currently using otherlanguages, such as C and Pascal, among others If you have experience in the Cprogramming language, much of what you see in the chapter will be familiar,with a few exceptions, of course This chapter will introduce the basics of theC++ programming language It is not designed to be an exhaustive tutorial orreference
Chapter 2, “Object Orientation—Theory and Practice,” introduces the threemajor concepts of object-oriented programming It also introduces some of thecommon terms used Chapter 3 addresses object-oriented programming usingC++ You will not find any How-Tos in this chapter addressing object-orientedprogramming
1.1 Writ e t he Sim plest C++ Program Wit hout Know ing
t he Language
The quickest way to learn to program in an unfamiliar language is to write asimple program and then analyze it In this How-To, you will write a verysimple program This program is really a template for a C++ program Theprogram in this How-To demonstrates the minimum a C++ program mustconsist of You are not required to know C or C++ to create this program Youwill, although, need a C++ compiler and linker and a text editor
1.2 Creat e a Program t o Perf orm Calculat ions
Most useful programs perform a repetitive task And almost every programperforms calculations of one type or another In this How-To, a program ispresented that will perform some simple calculations The program will introduce the use of program variables to hold data It also demonstrates some
of the popular mathematical operators Output operations (displaying text) ispresented, as well as acquiring input from the user
Trang 251.3 Use t he Various Loop St at em ent s That Are
Available in C++
In this How-To, you will write a program that uses the three C++ looping
constructs The three loops discussed are for, do-while, and while Input andoutput functionality is also demonstrated Looping statements are very
important for repetitive operations, such as accessing elements of an array, or
for visiting some finite or unknown number of objects, or for obtaining
continual input from a user
1.4 Creat e a Program That Uses One or M ore Funct ions
Most programming languages support the use of functions and/or procedures
In this How-To, you will be introduced to functions, including the declarationand definition of functions Argument passing is also shown; additionally,
returning values from functions is presented You will create a program that
uses the facilities of a function to perform a calculation
1.5 Use t he Derived Dat a Types Such As Arrays and
Point ers
Arrays and pointers are considered by many developers as difficult types to
work with This How-To should dispel that myth A program is presented in
this How-To to demonstrate the more common uses of these derived types Youwill create a function to perform a calculation and one to display a message andgather input from the user The C++ structis also introduced
1.6 Creat e Dat a When t he Program Is Running
The creation of data at runtime is introduced in this How-To You will learn
how to dynamically allocate memory for various data types Dynamically
creating memory at runtime is an important feature of C++; it allows you to
create only the objects that are required by your application The C++ operators
newand deleteare introduced
1.7 Creat e a Program t o Perf orm Error Handling,
Specif ically Except ion Handling
Error handling is important to the success of a program Invalid input, accesses
to hardware that is not available, and other program anomalies must be testedfor and handled gracefully This How-To presents the C++ exception handlingmechanism The C++ Standard defines a standardized method for handling
exceptions at runtime
CH A PT ER 1
A Q U I C K I N T R O D U C T I O N T O T H E L A N G U A G E 11
Trang 26C O M PL EX I T Y
B E G I N N I N G1.1 How do I…
Writ e t he sim plest C++ program
w it hout know ing t he language?
Problem
I would like to be able to write a C++ program without initially knowinganything about the language Is there a program I can write without having toknow what is required?
Technique
Most programmers investigate a new language by writing a simple program andthen go back to understand how it all works You can do this in C++, too At aminimum, you will need
• A C++ compiler and linker
• A text editor
You will use the editor to write the source text, referred to as source code.
Then you will use the compiler and linker to produce the program
Steps
1. You should create a base source code directory named SOURCEand thenchange to this directory Next, create a work directory named FIRSTandchange to it
2. Start your text editor In a pinch, you could use Notepad if you arerunning under Windows 95/NT If you are using UNIX, you could use ed
or vi Refer to your system documentation for details
3. Type in the following source code, exactly as shown Pay special attention
to symbols, such as brackets and semicolons
// filename: first.cpp - my first C++ program
#include <iostream>
using namespace std ; int main( ) /* main function */
{ cout << “My first C++ program!” << endl ; return( 0 ) ;
}
Trang 274. Save the file, naming it FIRST.CPP Then exit the editor and return to thecommand line.
5. At the command line, type the command required to run the compiler
and linker For example, if you are using Microsoft Visual C++, youwould type cl first.cpp The compiler will run and (if you typed alltext correctly) return to the command line without any error messages Ifthe compiler does report an error, refer to the following “Comments”
section
6. At the command prompt, type the name of the executable (called first)
If you are on a UNIX system and you do not see a file named first, lookfor a file named a.out; if you find this filename, execute it You shouldsee the following message on your screen:
My first C++ program!
In the next section, “How It Works,” I will discuss how this programoperates
How It Works
Now it is time to examine the process in more detail First, I will review the
processes that are required to create a program Then I will examine the sourcefile itself, line by line
The procedure to create a program is always the same First, you create
source code and save it in a file so that the compiler can parse it You can use
any text editor to type your source code If you are using Windows, you can
use Notepad or WordPad If you must use a word processor, be sure to save thefile as a pure ASCII text file If you are using UNIX, you can use vi, emacs, or
ed I recommend that you use a dedicated programmer’s editor for serious
source editing
The next step is to type the source code to satisfy the functionality for the
program Visual style for the source layout is important for both you and otherswho will be maintaining your source code A number of styles are accepted Seethe following “Comments” section for examples
After you have typed the source code and have saved the file, the compiler
must be run against the source file The compiler reads the source file, performsinterpretation, and produces an object file The object file, in its current form,cannot be executed directly
Next, the linker must be run to produce the executable The linker combinesthe object file(s), plus any required library functions and classes to produce theprogram The output of the linker, if everything is successful, is an executableprogram This program is now ready to run
1 1
W R I T E A S I M P L E C + + P R O G R A M W I T H O U T K N O W I N G T H E L A N G U A G E 13
Trang 28Now shift your attention to the source code itself and discover what eachline does.
The first line in the file is identified as a comment A comment in C++ can
be denoted in one of two ways One way, as is demonstrated in the example,consists of the two-character sequence //(two forward slashes) This style is
referred to as the line comment The compiler disregards any text beyond this
sequence The comment in this source text// filename: first.cpp - my first C++ program
simply tells any readers that the name of this file is first.cppand that this isyour first C++ program The second form of comment in C++ consists of twoindividual character sequences /*(slash-star) and */(star-slash) and is
commonly referred to as a block comment The sequence /*begins the commentand the sequence */ends the comment The difference between the two styles
is that block comments can span many lines, whereas the line comment cannot
In addition, program statements can exist after the block comment’s endsequence A block comment is shown in the following example:
int main( ) /* main function */
The second line of code in the file
The third line in the source fileusing namespace std ;
is a usingdirective and is used in conjunction with the namespace feature.Namespaces are used to partition the global namespace This eliminates, or atleast reduces, name conflicts Refer to the following “Comments” section for adiscussion of the usingdirective if your compiler complains
The function found on the fourth line of codeint main( ) /* main function */
is the starting point for a C++ program; the mainfunction is a requirement ofevery C++ program The intis a C++ data type and designates that the returnvalue from mainis an integer value In short, the operating system loads a
Trang 29program into memory and then calls the mainfunction to start the ball rolling.The body of the mainfunction is delineated by the opening and closing braces{} The “Comments” section that follows discusses an optional declaration of
main Functions will be discussed in How-To 1.4
The statement on the fifth line
cout << “My first C++ program!” << endl ;
displays a message to standard output (the screen) The insertion operator <<isused to put data to the coutobject Notice that the insertion operator can be
chained In the example, the first data item sent to the coutobject is a string oftext, followed by the endlmanipulator (Note that the last character in endlis
L, not the numeric value 1.) Finally, a semicolon is used to end the statement.The last line of code
return( 0 ) ;
is the returnstatement The returnstatement directs a function to return to itscaller; in this context, mainreturns to the operating system A return
expression can optionally return a value to its caller In this instance, the
returnstatement returns a zero to the operating system
That’s all that is required for a C++ program In this exercise, you have built
a very simple, yet straightforward C++ program All C++ programs must followthis “template.” The remainder of a program’s functionality is up to you to
develop This book consists of many examples you need to expand on this basicexample
Comments
Source code style is a hotly debated topic Every programmer develops his or
her own style of source code formatting The sample that follows is the
traditional K&R style:
The following sample is a variation of the block style and is known as
indented block style:
Trang 30The most widely accepted style is the second form, block style Block style ismore visually pleasing and the braces are easier to visually align.
The convention used for the filename identified in the #includecomplieswith the Standard C++ convention No extension is specifically identified forthe filename If your compiler complained that it could not open iostream, tryreplacing the statement:
#include <iostream>
with the following:
#include <iostream.h>
If your compiler does not conform to the new convention, it will try to find
a file named iostream Changing the name to iostream.hshould help If yourcompiler still complains with No such file or directory, you have one of
two problems Either you have a very old compiler or your compiler’s settings
are incorrect If you are using a very old compiler, I strongly suggest that youupgrade to one of the newer packages Why? The examples throughout thisbook assume you are using a current compiler package—older compilers mightnot understand some of the constructs used I also mentioned that the
compiler’s settings might be incorrect Specifically, check the settings that thecompiler uses for file locations, such as path settings or environment variables
If your compiler complains about the following source code line:
using namespace std ;
simply remove that line from the source file and recompile If the compiler nolonger complains, it does not support the namespacekeyword Alternatively,you can precede the text with the line comment //characters, as in thefollowing example:
//using namespace std ;
Remember that the compiler will ignore any source code beyond the linecomment sequence It is the decision of the compiler vendor whether to imple-ment a language feature or not; the only way to know is to try the feature orcheck the vendor’s documentation
The optional declaration for mainis the following:
int main( int argc, char *argv[] ) ;
The first argument, int argc, represents the number of command-line ments provided to the program The second argument, char *argv[], is anarray of pointers to char(specifically, to each of the arguments) Each argument
argu-to a C++ program is treated as a string of text You can pass information argu-to aprogram using arguments on the command line For example, the followingshows a program that accepts input to multiply two numbers:
Prompt> mult 114 23
Trang 31This example will read the two arguments, multiply the two values, and
display the result to the standard output
C O M PL EX I T Y
B E G I N N I N G1.2 How do I…
Creat e a program t o perf orm
calculat ions?
Problem
I would like to write a program that can perform some calculations I know that
I will have to use data variables, but I am unfamiliar with the various data typesand operators in C++
Technique
Programming languages provide data type variables that can be used to hold
values A value can be stored, accessed, and replaced in a variable In order touse a variable, you must decide the data type(s) that you need The C++
language defines a number of variable data types to choose from The programpresented in this How-To will calculate the number of inches for a specified
number of feet
Steps
1. Change to your base source directory and create a new directory named
TOINCH Then, start up your text editor
2. Type in the following source code, exactly as shown:
// toinch.cpp - converts feet to inches.
int numberOfInches = numberOfFeet * inchesInFoot ; cout << numberOfInches << “ inches are in “ ; cout << numberOfFeet << “ feet” << endl ;
1 2
C R E A T E A P R O G R A M T O P E R F O R M C A L C U L A T I O N S 17
Trang 32return( 0 ) ; }
3. Save the file, naming it TOINCH.CPP Then, exit out of the editor andreturn to the command line
4. Run the compiler and linker, naming TOINCH.CPPas the input file
5. Run the TOINCH program The following message will be displayed:Please enter the number of feet, I will tell you the number of inches
6. The cursor will be on the next line, awaiting input Enter the value 2 Theprogram will perform the calculation and display the following message:
24 inches are in 2 feet
7. To perform another calculation, simply rerun the program
This source line also introduces the assignment operator = The assignmentoperator is used to place the value on the right-hand side of the operator to thevariable on the left-hand side In this example, the value 12is placed in thevariable named inchesInFoot The constant (variable) inchesInFootwill holdthis value throughout the life of the program (its value cannot be changed) Thenext line of code is the following:
int numberOfFeet = 0 ;
Trang 33This int, named numberOfFeetis declared and initialized to a value of 0.
The purpose of this variable is to hold the number of feet that the user specifies
at runtime Note that the constmodifier is not applied to this variable
definition because numberOfFeet’s contents will need to be changed The nexttwo lines
cout << “Please enter the number of feet, “ ;
cout << “I will tell you the number of inches” << endl ;
are used to output a message (an instruction) to the user Notice that althoughthe two statements are independent and exist on two separate lines, the
message is actually displayed to the user as a single line The endlmanipulatorperforms two operations First, it flushes the output buffer and outputs a
newline character Because output is to the screen, the cursor will be placed onthe next line, flush with the left margin Because the first coutstatement doesnot end with an endl, the second message is appended to the first The next
line of code
cin >> numberOfFeet ;
awaits input from the user After the user enters a value and presses the Enter
key, the cinobject will take the value and place it in the variable named
numberOfFeet The cinstatement actually performs a conversion behind the
scenes You press the keyboard character 2; cintakes this character and
converts it to a C++ integer type and places the value in the variable This
brings you to the next line of code:
int numberOfInches = numberOfFeet * inchesInFoot ;
This statement introduces the multiplication operator * This operator is one
of many defined by the C++ language This source line is referred to as a
compound statement First, the intvariable numberOfInchesis declared for use.Next, the value stored in numberOfFeetis multiplied by the value stored in
inchesInFoot The result of this expression is then assigned to the variable
numberOfInches The next two source lines
cout << numberOfInches << “ inches are in “ ;
cout << numberOfFeet << “ feet” << endl ;
display the result of the conversion to the standard output Notice that you canstream different data types to the coutobject First, the value stored in
numberOfInchesis sent to cout, followed by a string In the next statement,
numberOfFeetis sent to cout, followed by another string, and finally the endl
manipulator
The last program statement, the returnstatement, returns the value 0
returns to the operating system
1 2
C R E A T E A P R O G R A M T O P E R F O R M C A L C U L A T I O N S 19
Trang 34The C++ language defines a number of data types: bool, char, int, long,
float, and double A boolis used to represent a Boolean value, either trueor
false The chartype is used to contain characters, such as 3, #, or m The types
intand longare integral types and can hold whole numbers only The types
floatand doubleare used for storing floating-point numbers
In C++, strings are implemented as an array of char In fact, any data typecan be declared as an array You will look at arrays in a How-To later in thischapter
The constkeyword is used to qualify a declaration You must remember toinitialize the constvariable at the point of declaration; if you don’t, you will not
be able to assign to it For example, the compiler will not allow the following:const int inchesInFoot ;
inchesInFoot = 12 ; // error right here!
The constvariable is used as a symbolic constant (or alias) for a value.Using a symbolic name provides a descriptive name for some value An additional benefit of using constis that the value stored in the variable isprotected from modification It also helps with code maintenance Why? Let’slook at a brief example The following example defines a charthat is constant.Assume that the charis used as a choice within a menu system
const char REPLACE_OPTION = ‘S’ ; // replace
words, you would have to search for all occurrences of the letter Sand change
them to the new value Instead, by using a constant, you only have to changethe initialization value of the constant declaration The following line of codeshows a decision to change the value of REPLACE_OPTIONto R:
const char REPLACE_OPTION = ‘R’ ;
The change is only required at the declaration The next step would be torecompile all the code associated with this change You do not have to worryabout searching for every occurrence of Rbecause the compiler will do all thework required
The cinobject is used to accept data from the standard input; the default isthe keyboard The extraction operator >>directs the input from the cinobject
to the named variable(s) In the previous example, numberOfFeetis the ient of data from cin
Trang 35recip-C O M PL EX I T Y
B E G I N N I N G1.3 How do I…
Use t he various loop st at em ent s
t hat are available in C++?
Problem
I have started to sink my teeth into C++ now by writing very simple programs
I need to extend my knowledge of the language and have considered using a
loop statement as I’ve seen in other languages I need to know the various loopsavailable in C++ and how to use them
Technique
Looping techniques in C++ are essentially the same as they are in other
languages The loop names might be different, but for the most part, they servethe same purposes The C++ language serves up three different types of loopingstatements: for, do-while, and while The following example will show all
three in action
Steps
1. Change to your base source directory and create a new directory named
LOOP Next, fire up your text editor
2. Type in the following source code, exactly as shown:
// loop.cpp - program to demonstrate C++ loops
#include <iostream>
using namespace std ; int main()
{ int value = 0 ; cout << “Beginning of while loop” << endl ; while( value < 5 )
{ cout << “The value of value is: “ << value << endl ; ++value ;
} cout << “End of while loop” << endl ; cout << “\nBeginning of do-while loop” << endl ;
do { cout << “The value of value is: “ << value << endl ; }while( value < 5 ) ;
cout << “End of do-while loop” << endl ;
1 3
U S E T H E V A R I O U S L O O P S TA T E M E N T S T H A T A R E A V A I L A B L E I N C + + 21
Trang 36cout << “\nBeginning of for loop” << endl ; for( value = 0; value < 5; value++ ) {
cout << “The value of value is: “ << value << endl ; }
cout << “End of for loop” << endl ; return 0 ;
}
3. Save the file as LOOP.CPPand exit the editor to the command line
4. Compile and link the LOOP.CPPsource file
5. Run the program; the output should be as follows:
Beginning of while loop The value of value is: 0 The value of value is: 1 The value of value is: 2 The value of value is: 3 The value of value is: 4 End of while loop Beginning of do-while loop The value of value is: 5 End of do-while loop Beginning of for loop The value of value is: 0 The value of value is: 1 The value of value is: 2 The value of value is: 3 The value of value is: 4 End of for loop
How It Works
Starting with the sixth line of code, an inthas been declared and initializedwith a value of 0 This integer variable will be used by all three loops In addition to demonstrating loops, this How-To introduces you to the C++ increment (++) and less-than (<) operators
The next statement sends a message to the screen:
cout << “Beginning of while loop” << endl ;
It is always a good idea to let the user know what is going on within aprogram You can consider these messages as “progress reports.”
You begin your investigation of C++ loops with the next line of code:while( value < 5 )
Trang 37The whileloop is a precondition (entry condition) loop First, the test
expression within the parentheses is evaluated If the result of the expression isnon-zero (true), the statement(s) within the whileloop’s body are executed Ifthe result of the expression is 0(false), then the loop exits and control returns
to the first statement after the whileloop’s body This loop can be verbally
expressed as follows: “While the value stored in valueis less than 5, execute
the statements within the loop’s body.” It is possible for a loop to never execute
if the expression is initially false For example, if the variable valueis initiallyset to 20, the whileloop will never execute
An opening brace begins the body of a whileloop and a closing brace endsthe body All statements within the body are executed as long as the loop’s
expression is true The whileloop contains two statements, a message that
displays the contents of the variable valueand an increment (++) expression
You have seen the coutstatement before; its job is to display data to the
standard output The next statement uses the increment operator ++ This
operator simply increments the value of the operand by one It is shorthand forthe following statement:
value = value + 1 ;
Two versions of the increment operator exist: prefix increment and postfix
increment The version used in the whileloop is the prefix increment operator.The prefix increment version increments a variable first and then evaluates thebalance of the expression The postfix increment version does the opposite: Theexpression is evaluated first, and then the variable is incremented The
following example shows the difference:
Line 1: if( ++check < 6 )
Line 2: if( check++ < 6 )
Assume the value of check is 5before the ifstatement In line 1, the value
of checkis incremented first, and then the expression is evaluated Because
checkis now 6, the expression evaluates to false(check < 6) and the
statements within if’s body are not executed In line 2, the expression within
the ifstatement (check < 6) evaluates to true, checkis incremented by 1
Because the expression evaluates to true, the statements within the if’s body
are executed
After valueis incremented, program control is returned to the top of the
whileloop The whileloop’s expression is again evaluated and if it is non-zero,the body is again executed; otherwise, the program exits the loop and control
jumps to the first statement after the whileloop’s body In this example, it is amessage to the user that the whileloop has ended
The next statement displays a message announcing the beginning of the
do-whileloop A do-whileloop is a postcondition (exit condition) loop A
do-whileloop is always executed once, even if the test expression evaluates to
1 3
U S E T H E V A R I O U S L O O P S TA T E M E N T S T H A T A R E A V A I L A B L E I N C + + 23
Trang 38false This behavior is in contrast to the whileloop Note that the valuecontained in valueis still 5, yet the coutstatement is still executed The testexpression within the whileportion is evaluated as falseand the loop isterminated Control resumes at the coutstatement announcing the end of the
Next, you come to the forloop The forloop consists of three expressions.The first expression is initialization, followed by a test expression, and finally,the update (or change) expression; each expression is separated by a semicolon.The following is the program’s forloop:
for( value = 0; value < 5; value++ )
First, valueis initialized to 0 The middle expression (value < 5) is the testexpression The test expression is evaluated; if the result is true, the loop’sbody is executed, otherwise, the program exits the loop After all statements inthe body have executed, the third expression is evaluated After the thirdexpression is evaluated, control returns to the test expression
Comments
Each of the C++ loops can have either a single statement or multiple statementsenclosed within braces All of the loop examples in this How-To use braces todelineate the loop’s body For example, the forloop can be written this way:for( value = 0; value < 5; value++ )
cout << “The value of value is: “ << value << endl ;
You can do this because this forloop only has one statement associated with
it It is more appropriate to use braces, even if you only have one statementassociated with a loop The reason is that if you come back to add anotherstatement to the single-statement loop, you might forget to add the braces Todemonstrate, assume you want to add a calculation that is performed for everyiteration of the loop
for( value = 0; value < 5; value++ )
cout << “The value of value is: “ << value << endl ;
paycheckAmount = hours * value ;
Everything appears fine; the indentation shows that the new statement ispart of the loop’s body Don’t be fooled by appearances By visual inspection, it
appearsthat the program will execute both statements following the forsion In reality, only the first statement will execute for every iteration of theloop The second statement will only execute after the loop is finished Tocorrect the problem, the source code needs to look like the following:
expres-for( value = 0; value < 5; value++ )
{
cout << “The value of value is: “ << value << endl ;
paycheckAmount = hours * value ;
}
Trang 39Now, everything will work as expected.
The third (update) expression in a forloop is not restricted to using the
increment operator ++ You might want to use the decrement operator Youcan also increment the value by two, three, or more The expression can also bethe result of a multiplication The following will increment valueby 20in thethird expression:
for( value = 1; value < 100; value = value + 20 )
Creat e a program t hat uses one or
m ore f unct ions?
Problem
I am ready to move on to the more advanced features of the C++ language,
specifically functions I know that functions are used to accomplish specific
tasks I need to know how to declare and define functions
Technique
Functions in C++ are the basic building blocks to modularize a program The
technique for creating functions in C++ is the same as it is in any other
language You must decide the specific functionality required for your
application If possible, you should make your functions as general as possible.This allows you to use a function in other programs
Steps
1. Change to the base source directory and create a directory named FUNC
2. Start up your text editor and type in the following source code:
// func.cpp - program to demonstrate a function in C++
#include <iostream>
using namespace std ; long multiply( long left, long right ) ; int main()
{ long value1 = 0, value2 = 0 ;
1 4
C R E A T E A P R O G R A M T H A T U S E S O N E O R M O R E F U N C T I O N S 25
Trang 40cout << “\nProgram to multiply two integers “ ; cout << “and display the result “ << endl ; for( long result = 1; result != 0; /*empty expression*/ ) {
value1 = value2 = result = 0 ; cout << “\nTwo zeros will end the program.” << endl ; cout << “Enter the first integer (and enter key): “ ; cin >> value1 ;
cout << “Enter the second integer (and enter key): “ ; cin >> value2 ;
if( value1 == 0 && value2 == 0 ) break ;
result = multiply( value1, value2 ) ; cout << value1 << “ multiplied by “ ; cout << value2 << “ = “ << result << endl ; }
return 0 ; }
// Multiplies the two arguments // together and returns the results long multiply( long left, long right ) {
long result = left * right ; return( result ) ;
}
3. Save the file as LOOP.CPPand exit the editor to the command line
4. Compile and link the LOOP.CPPsource file
5. Run the program; the output should be as follows:
Program to multiply two integers and display the result.
Two zeros will end the program.
Enter the first integer: 4 Enter the second integer: 4
4 multiplied by 4 = 16
How It Works
If you have been following the previous How-Tos, you will notice a new line ofcode after the using namespace stdline:
long multiply( long left, long right ) ;
This is referred to as a function declaration It is the function’s signature The
declaration specifies the number or arguments, if any, and their data type Thedeclaration also shows the return type (if the function returns a value) In this