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

Object Oriented Programming in C++ ppt

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 (10.28 MB, 988 trang )

Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore
ISBN: 157169160x
Publication Date: 11/25/98
Bottom of Form
Previous
Table of Contents
Next
Preface
The major changes to this Third Edition are concerned with Standard C
++
and object-oriented design. In
addition, the book is no longer geared exclusively to Borland C
++
compilers.
Standard C
++
, finalized in the fall of 1997, introduced many new features to C
++
. Some of these features,
such as templates and exceptions, had already been adopted by compiler manufacturers. However, the
Standard Template Library (STL) has only recently been included in compilers. This book adds a chapter
on the STL.
We’ve also introduced other features from Standard C
++
, including new header files, the
string
class,
new-style casts, namespaces, and so on.
The design of object-oriented programs has received increasing emphasis in recent years, so we’ve added


a chapter on object-oriented design.
The advent of Standard C
++
means that, at least to a greater extent than before, all compilers should treat
source code in the same way. Accordingly, we’ve modified our emphasis on Borland compilers, and now
focus on code that should work with any Standard C
++
compiler. Of course, the reality seldom matches
the ideal, so so the programs in this book have been tested with both Microsoft and Borland compilers,
and modified when necessary to work with both of them.
Previous
Table of Contents
Next
Page 1
ABC Amber CHM Converter Trial version, />Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore
ISBN: 157169160x
Publication Date: 11/25/98
Bottom of Form
Previous
Table of Contents
Next
About the Author
Robert Lafore has been writing books about computer programming since 1982. His best-selling titles
include Assembly Language Programming for the IBM PC, C Programming Using Turbo C
++
, C
++
Interactive Course, and Data Structures and Algorithms in Java. Mr. Lafore holds degrees in

mathematics and electrical engineering, and has been active in programming since the days of the PDP-5,
when 4K of main memory was considered luxurious. His interests include hiking, windsurfing, and
recreational mathematics.
Acknowledgments to the Third Edition
I’d like to thank the entire team at Macmillan Computer Publishing. In particular, Tracy Dunkelberger
ably spearheaded the entire project and exhibited great patience with what turned out to be a lengthy
schedule. Jeff Durham handled the myriad details involved in interfacing between me and the editors with
skill and good humor. Andrei Kossorouko lent his expertise in C
++
to ensure that I didn’t make this
edition worse instead of better.
Acknowledgments to the Second Edition
My thanks to the following professor—susers of this book as a text at their respective colleges and
universities—for their help in planning the second edition: Dave Bridges, Frank Cioch, Jack Davidson,
Terrence Fries, Jimmie Hattemer, Jack Van Luik, Kieran Mathieson, Bill McCarty, Anita Millspaugh, Ian
Moraes, Jorge Prendes, Steve Silva, and Edward Wright.
I would like to thank the many readers of the first edition who wrote in with corrections and suggestions,
many of which were invaluable.
At Waite Group Press, Joanne Miller has ably ridden herd on my errant scheduling and filled in as
academic liaison, and Scott Calamar, as always, has made sure that everyone knew what they were
doing. Deirdre Greene provided an uncannily sharp eye as copy editor.
Thanks, too, to Mike Radtke and Harry Henderson for their expert technical reviews.
Special thanks to Edward Wright, of Western Oregon State College, for reviewing and experimenting
with the new exercises.
Acknowledgments to the First Edition
My primary thanks go to Mitch Waite, who poured over every inch of the manuscript with painstaking
attention to detail and made a semi-infinite number of helpful suggestions.
Bill McCarty of Azusa Pacific University reviewed the content of the manuscript and its suitability for
classroom use, suggested many excellent improvements, and attempted to correct my dyslexic spelling.
Page 2

ABC Amber CHM Converter Trial version, />George Leach ran all the programs, and, to our horror, found several that didn’t perform correctly in
certain circumstances. I trust these problems have all been fixed; if not, the fault is entirely mine.
Scott Calamar of The Waite Group dealt with the myriad organizational aspects of writing and producing
this book. His competence and unfailing good humor were an important ingredient in its completion.
I would also like to thank Nan Borreson of Borland for supplying the latest releases of the software
(among other useful tidbits), Harry Henderson for reviewing the exercises, Louise Orlando of The Waite
Group for ably shepherding the book through production, Merrill Peterson of Matrix Productions for
coordinating the most trouble-free production run I’ve ever been involved with, Juan Vargas for the
innovative design, and Frances Hasegawa for her uncanny ability to decipher my sketches and produce
beautiful and effective art.
Dedication
This book is dedicated to GGL another inodomitable spirit.222
Tell Us What You Think!
As 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 we could 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 you did or didn’t like about this book—as well as what we can do to make our books 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 as your name and phone or
fax number. I will carefully review your comments and share them with the author and editors who
worked on the book.
Fax:
317-817-7070
Email:


Mail:

Tracy Dunkelberger
Executive Editor
Advanced Programming and Distributed Architectures
Macmillan Computer Publishing
201 West 103rd Street
Indianapolis, IN 46290 USA
Previous
Table of Contents
Next
Page 3
ABC Amber CHM Converter Trial version, />Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore
ISBN: 157169160x
Publication Date: 11/25/98
Bottom of Form
Previous
Table of Contents
Next
APPENDIX A
ASCII Chart
Table A.1 IBM Character Codes
DEC
HEX
Symbol
Key
Use in C
0
00
(NULL)

Ctrl 2
1
01
A

Ctr A
2
02
B

Ctrl B
3
03
C

Ctrl C
4
04
D

Ctrl B
5
05
E

Ctrl E
6
06
F


Ctrl F
7
07
G

Ctrl G
Beep
8
08
H

Backspace
Backspace
9
09
I

Tab
Tab
10
0A
J

Ctrl J
Linefeed (new line)
11
0B
K

Ctrl K

Vertical Tab
12
0C
L

Ctrl L
Form Feed
13
0D
M

Enter
Carriage Return
14
0E
N

Ctrl N
15
0F
O

Ctrl O
16
10
P

Ctrl P
17
11

Q

Ctrl Q
18
12
R

Ctrl R
19
13
S

Ctrl S
20
14
T

Ctrl T
21
15
U

Ctrl U
22
16
_

Ctrl V
23
17

W

Ctrl W
24
18
X

Ctrl X
25
19
Y

Ctrl Y
26
1A
Z

Ctrl Z
27
1B
a

Escape
Page 4
ABC Amber CHM Converter Trial version, />28
1C
b

Ctrl \
29

1D
c

Ctrl ]
30
1E
d

Ctrl 6
31
1F
e

Ctrl –
32
20
SPACE BAR
33
21
!
!
34
22


35
23
#
#
36

24
$
$
37
25
%
%
38
26
&
&
39
27


40
28
(
(
41
29
)
)
42
2A
*
*
43
2B
+

+
44
2C
,
,
45
2D


46
2E
.
.
47
2F
/
/
48
30
0
0
49
31
1
1
50
32
2
2
51

33
3
3
52
34
4
4
53
35
5
5
54
36
6
6
55
37
7
7
56
38
8
8
57
39
9
9
58
3A
:

:
59
3B
;
;
60
3C
<
<
61
3D
=
=
62
3E
>
>
63
3F
?
?
64
40
@
@
65
41
A
A
66

42
B
B
67
43
C
C
Page 5
ABC Amber CHM Converter Trial version, />68
44
D
D
69
45
E
E
70
46
F
F
71
47
G
G
72
48
H
H
73
49

I
I
74
4A
J
J
75
4B
K
K
76
4C
L
L
77
4D
M
M
78
4E
N
N
79
4F
O
O
80
50
P
P

81
51
Q
Q
82
52
R
R
83
53
S
S
84
54
T
T
85
55
U
U
86
56
V
V
87
57
W
W
88
58

X
X
89
59
Y
Y
90
5A
Z
Z
91
5B
[
[
92
5C
\
\
93
5D
]
]
94
5E
^
^
95
5F
_
_

96
60
'
'
97
61
a
a
98
62
b
b
99
63
c
c
100
64
d
d
101
65
e
e
102
66
f
f
103
67

g
g
104
68
h
h
105
69
i
i
106
6A
j
j
107
6B
k
k
Page 6
ABC Amber CHM Converter Trial version, />108
6C
l
l
109
6D
m
m
110
6E
n

n
111
6F
o
o
112
70
p
p
113
71
q
q
114
72
r
r
115
73
s
s
116
74
t
t
117
75
u
u
118

76
v
v
119
77
w
w
120
78
x
x
121
79
y
y
122
7A
z
z
123
7B
{
{
124
7C
|
|
125
7D
}

}
126
7E
~
~
127
7F
f
Ctrl
128
80

Alt 128
129
81

Alt 129
130
82

Alt 130
131
83

Alt 131
132
84

Alt 132
133

85

Alt 133
134
86

Alt 134
135
87

Alt 135
136
88

Alt 136
137
89

Alt 137
138
8A

Alt 138
139
8B
ù
Alt 139
140
8C


Alt 140
141
8D

Alt 141
142
8E

Alt 142
143
8F

Alt 143
144
90

Alt 144
145
91

Alt 145
146
92

Alt 146
147
93

Alt 147
Page 7

ABC Amber CHM Converter Trial version, />148
94

Alt 148
149
95
ũ
Alt 149
150
96

Alt 150
151
97

Alt 151
152
98

Alt 152
153
99

Alt 153
154
9A
ĩ
Alt 154
155
9B


Alt 155
156
9C
Ê
Alt156
157
9D
Ơ
Alt157
158
9E

Alt158
159
9F

Alt159
160
A0

Alt160
161
A1

Alt161
162
A2
ú
Alt162

163
A3

Alt163
164
A4

Alt164
165
A5

Alt165
166
A6
a
Alt166
167
A7
o
Alt167
168
A8
đ
Alt168
169
A9
â
Alt169
170
AA


Alt170
171
AB
'
Alt 171
172
AC

Alt 172
173
AD
Ă
Alt 173
174
AE
ô
Alt 174
175
AF

Alt 175
176
B0
Ô
Alt 176
177
B1
Ô
Alt 177

178
B2
Ô
Alt 178
179
B3

Alt 179
180
B4
Ơ
Alt 180
181
B5
à
Alt 181
182
B6

Alt 182
183
B7

Alt 183
184
B8

Alt 184
185
B9


Alt 185
186
BA

Alt 186
187
BB
a
Alt 187
Page 8
ABC Amber CHM Converter Trial version, />188
BC
o
Alt 188
189
BD
Ω
Alt 189
190
BE
æ
Alt 190
191
BF

Alt 191
192
C0
¿

Alt 192
193
C1
¡
Alt 193
194
C2
¬
Alt 194
195
C3

Alt 195
196
C4

Alt 196
197
C5

Alt 197
198
C6
Δ
Alt 198
199
C7
«
Alt 199
200

C8
»
Alt 200
201
C9

Alt 201
202
CA
g
Alt 202
203
CB
À
Alt 203
204
CC
Ã
Alt 204
205
CD
Õ
Alt 205
206
CE
Œ
Alt 206
207
CF
œ

Alt 207
208
D0

Alt 208
209
D1

Alt 209
210
D2
"
Alt 210
211
D3
"
Alt 211
212
D4
Ô
Alt 212
213
D5
"
Alt 213
214
D6
÷
Alt 214
215

D7

Alt 215
216
D8
ÿ
Alt 216
217
D9
Ÿ
Alt 217
218
DA
/
Alt 218
219
DB
¤
Alt 219
220
DC
<
Alt 220
221
DD
>
Alt 221
222
DE
fi

Alt 222
223
DF
fl
Alt 223
224
E0
α
Alt 224
225
E1
β
Alt 225
226
E2
Γ
Alt 226
227
E3
π
Alt 227
Page 9
ABC Amber CHM Converter Trial version, />228
E4
ς
Alt 228
229
E5
Â
Alt 229

230
E6
µ
Alt 230
231
E7
τ
Alt 231
232
E8
Ë
Alt 232
233
E9
Θ
Alt 233
234
EA
Ω
Alt 234
235
EB
Î
Alt 235
236
EC
Ï
Alt 236
237
ED

ψ
Alt 237
238
EE

Alt 238
239
EF
Ô
Alt 239
240
F0

Alt 240
241
F1
+
Alt 241
242
F2

Alt 242
243
F3

Alt 243
244
F4
Ù
Alt 244

245
F5
1

Alt 245
246
F6
÷
Alt 246
247
F7

Alt 247
248
F8
°
Alt 248
249
F9

Alt 249
250
FA
.
Alt 250
251
FB

Alt 251
252

FC
η
Alt 252
253
FD
²
Alt 253
254
FE
<
Alt 254
255
FF
(blank)
Alt 255
Those key sequences consisting of “Ctrl” are typed by pressing the CTRL key, and while it is being held
down, pressing the key indicated. These sequences are based on those defined for PC Personal
Computer series keyboards. The key sequences may be defined differently on other keyboards.
IBM Extended ASCII characters can be displayed by pressing the Alt key and then typing the decimal
code of the character on the keypad.
Previous
Table of Contents
Next
Page 10
ABC Amber CHM Converter Trial version, />Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore
ISBN: 157169160x
Publication Date: 11/25/98
Bottom of Form

Previous
Table of Contents
Next
APPENDIX B
STANDARD C++ KEYWORDS
Keywords implement specific C
++
language features. They cannot be used as names for variables or other
user-defined program elements. Many of the keywords are common to both C and C
++
, while others are
specific to C
++
. Some compilers may support additional keywords, which usually begin with one or two
underscores, as in
_cdecl
or
__int16
.
A
asm

auto

B
bool

break

C

case

catch

char

class

const

const_cast

continue

D
default

delete

do

double

dynamic_cast

E
else

enum


explicit

export

extern

F
false

Page 11
ABC Amber CHM Converter Trial version, />float

for

friend

G
goto

I
if

inline

int

L
long

M

main

mutable

N
namespace

new

O
operator

P
private

protected

public

R
register

reinterpret_cast

return

S
short

signed


sizeof

static

static_cast

struct

switch

T
template

this

throw

true

try

typedef

Page 12
ABC Amber CHM Converter Trial version, />typeid

typename

U

union

unsigned

using

V
virtual

void

volatile

W
wchar_t

while

Previous
Table of Contents
Next
Page 13
ABC Amber CHM Converter Trial version, />Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore
ISBN: 157169160x
Publication Date: 11/25/98
Bottom of Form
Previous
Table of Contents

Next
APPENDIX C
MICROSOFT VISUAL C++
This appendix tells you how to use Microsoft Visual C
++
to create console-mode applications, which are
the kind of applications used in this book. This discussion is based on Visual C
++
version 5.0.
The present version of Visual C
++
has good (although not perfect) adherence to Standard C
++
. It comes in
various versions, including a student version for under $100.
We’ll assume that Visual C
++
is installed in your system, and that you know how to start it by using the
Windows Start button and navigating to the appropriate menu item: Microsoft Visual C
++
.
You’ll want to make sure you can see file extensions (like
.CPP
) when operating MVC
++
. In Windows
Explorer, make sure that the option Hide MS-DOS File Extensions for File Types That are Registered is
not checked.
Screen Elements
When you start Microsoft Visual C

++
you’ll see that the resulting application is actually called Microsoft
Developer Studio. The studio can work with other languages besides C
++
, but we won’t worry about that
here.
The Developer Studio window is initially divided into three parts. On the left is the View Pane. This has
three tabs, for ClassView, FileView, and InfoView. Once you have a project going, the ClassView tab will
show you the class hierarchy of your program, and FileView will show you the files used in the project.
InfoView allows you to navigate through the documentation and help file structure. Click the plus signs to
expand the hierarchies, then double-click the document you want to read.
The largest part of the screen usually holds a document window. It can be used for various purposes,
including displaying your source files. It can also display the contents of help files. At the bottom of the
screen is a long window with more tabs: Build, Debug, and so on. This will display messages when you
perform operations such as compiling your program.
Single-File Programs
It’s easy to build and execute a single-file console program using Microsoft Visual C
++
. There are two
possibilities: the file already exists or the file needs to be written.
In either case you should begin by making sure that no project is currently open. (We’ll discuss projects in
a moment.) Click the File menu. If the Close Workspace item is active (not grayed) click it to close the
current workspace.
Building an Existing File
Page 14
ABC Amber CHM Converter Trial version, />If the
.CPP
source file already exists, as it does for the example programs in this book, select Open from the
File menu. (Note that this is not the same as Open Workspace.) Use the Open dialog box to navigate to
the appropriate file, select it, and click the Open button. The file will appear in the document window. (If

you’re compiling an example program that uses Console Graphics Lite, such as the
CIRCSTRC
program in
Chapter 5, “Functions,” or the
CIRCLES
program in Chapter 6, “Objects and Classes,” turn to the section
“Building Console Graphics Lite Programs.”)
To compile and link this file, select Build from the Build menu. A dialog box will appear asking if you want
to create a Default Project Workspace. Click Yes. The file will be compiled and linked with any necessary
library files.
To run the program, select Execute from the Project menu. If all goes well, a console window will appear
with the program’s output displayed in it.
When the program terminates, you’ll see the phrase Press any key to continue. The compiler arranges for
this to be inserted following the termination of any program. It keeps the console display on the screen long
enough to see the program’s output.
You can also run programs directly from MS-DOS. In Windows 95 and 98, you can obtain a box for
MS-DOS by clicking the Start button, selecting Programs and then the MS-DOS Prompt item. In the
resulting window you’ll see what’s called the C-prompt: the letter C, usually followed by the name of the
current directory. You can navigate from one directory to another by typing cd (for Change Directory) and
the name of the new directory. To execute a program, including any of the examples from this book, make
sure you’re in the same directory as the appropriate
.EXE
file, and type the name of the program (with no
extension). You can find out more about MS-DOS using the Windows help system.
Writing a New File
To start writing your own
.CPP
file, select New from the File menu and click the Files tab. Select C
++
Source File, and click OK. A blank document window will appear. Type in your program. Save the new

file by selecting Save As from the File menu, navigating to the correct directory, and typing the file name
with the
.CPP
extension (such as
myProg.cpp
). As before, select Build from the Build menu and click Yes to
the default workspace question. Your program will be compiled and linked.
If there are errors, they will appear in the Build window at the bottom of the screen. (You may need to
click the Build tab to make this window appear.) If you double-click the error line, an arrow will appear
next to the line containing the error in the source file. Also, if you position the cursor on the error number in
the Build window (such as C2143) and press the F1 key, an explanation of the error will appear in the
document window. You can correct the errors and repeat the build process until the message reads “0
error(s), 0 warning(s).” To execute the program, select Execute from the Build menu.
Before working on a new program, don’t forget to select Close Workspace from the File menu. This
ensures that you begin with a clean workspace. To open a program you’ve already built, select Open
Workspace from File menu, navigate to the right directory, and double-click the file with the appropriate
name and the
.DSW
extension.
Run-Time Type Information (RTTI)
A few programs, such as
EMPL_IO.CPP
in Chapter 12, “Streams and Files,” use RTTI. With Microsoft
Visual C
++
you need to enable a compiler option to make this feature work. Select Settings from the
Project menu and click the C/C
++
tab. From the Category list box, select C
++

Language. Click the
checkbox named Enable Run-Time Type Information. This will avoid various compiler and linker errors,
some of which are misleading.
Page 15
ABC Amber CHM Converter Trial version, />Multifile Programs
We’ve shown the quick and dirty approach to building programs. This approach works with one-file
programs. When projects have more than one file things become slightly more complicated. We’ll start by
reviewing what’s meant by the terms workspace and project.
Projects and Workspaces
Visual C
++
uses a concept called a workspace, which is one level of abstraction higher than a project. A
workspace can contain many projects. It consists of a directory and several configuration files. Within it,
each project can have its own directory, or the files for all the projects can simply reside in the workspace
directory.
Conceptually it’s probably easiest, at least for the small programs in this book, to assume that every
project has its own separate workspace. That’s what we’ll assume in this discussion.
A project corresponds to an application (program) that you’re developing. It consists of all the files needed
to create that application as well as information about how these files are to be combined. The result of
building a project is usually a single
.EXE
file that a user can execute. (Other results are possible, such as
.DLL
files.)
Source Files Already Exist
Let’s assume that the files you want to include in a new project already exist, and that they are in a
particular directory. Select New from the File menu, and click the Projects tab in the New dialog box.
Select Win32 Console Application from the list. First, in the Location box, type the path to the directory,
but do not include the directory name itself. Next, type the name of the directory containing the files in the
Project Name box. (By clicking the button to the right of the Location field you can navigate to the

appropriate directory, but make sure to delete the directory name itself from the location field.) Make sure
the Create New Workspace box is checked, and click OK.
For example, if the files are in
C:\Book\Ch13\Elev
, then you would first type C:\Book\Ch13\ in the Location
field and then Elev in the Project Name field. When you type the project name, it’s automatically added to
the location. (If it was there already it would be added again, resulting in a location of
C:\Book\Ch13\Elev\Elev
, which is not what you want.)
At this point various project-oriented files, with extension
.DSP,

.DSW
, and so forth, have been added to the
directory.
Now you need to add your source files to the project. This includes both
.CPP
and
.H
files. Select Add To
Project from the Project menu, click Files, select the files you want to add, and click OK. You can review
the files you’ve selected by clicking the FileView tab and then the plus sign for the project. You can also
see the class structure, complete with member functions, by clicking the ClassView tab.
To open a file so you can see it and modify it, select Open from the File menu and select the file.
Sometimes a file (such as the
msoftCon.h
file necessary for console graphics programs) is not in the same
directory as the other source files for your program. You can nevertheless add it to your project in the
same way that you add other files. Select Add To Project from the Project menu, select Files, and then
navigate to the file you want (or type in the complete pathname).

Saving, Closing, and Opening Projects
Page 16
ABC Amber CHM Converter Trial version, />To save the project, select Save Workspace. To close the project, select Close Workspace. (Answer Yes
to the query Close All Document Windows.) To open an existing project, select Open Workspace from
the file menu, navigate to the proper directory, select the
.DSW
file, and click Open.
Compiling and Linking
As with one-file programs, the easiest way to compile, link, and run a multifile program is to select Execute
from the Build menu. You can compile and link your project without running it by selecting Build from the
Build menu.
Building Console Graphics Lite Programs
Building programs that use the Console Graphics Lite functions (described in Appendix E, “Console
Graphics Lite”) requires some steps in addition to those needed for ordinary example programs. Programs
that use these functions should include the line
#include “msoftcon.h”
.
• Open the source file for the program as described earlier.
• Select Build from the Build menu. Answer Yes when asked if you want to create a default
project workspace. A project will be created, but the compiler will complain it can’t find
MSOFTCON.H.

• To tell it where to find this file, select Options from the Tools menu. Click on the Directories tab.
Select Include Files from the Show Directories For list. On the bottom line of the Directories list,
type the complete pathname of the directory where
MSOFTCON.H
is stored. (This directory should
be called
MSOFTCON
.) Click on OK.

• Now try building your file again. Now the compiler can find the header file, but there will be
numerous linker errors because the linker doesn’t know where to find the code for the graphics
functions. This code is in
MSOFTCON.CPP.

• Select Add To Project from the Project menu; then select Files. In the resulting dialog box
(called Insert Files into Project), navigate to the
MSOFTCON
directory. Select the
MSOFTCON.CPP
file. Click OK.
Now your program should compile and link correctly. Select Execute from the Build menu to see it run.
Debugging
In Chapter 3, “Loops and Decisions,” we suggest using the debugger to provide an insight into how loops
work. Here’s how to do that with Microsoft Visual C
++
. These same steps can help you debug your
program if it behaves incorrectly. We’ll be discussing one–file programs here, but the same approach
applies, with appropriate variations, to larger multifile programs.
Start by building your program as you normally would. Fix any compiler and linker errors. Make sure your
program listing is displayed in the Edit window.
Single Stepping
To start the debugger, simply press the F10 key. You’ll see a yellow arrow appear in the margin of the
listing, pointing to the opening brace following main.
If you want to start somewhere other than the beginning of the program, position the cursor on the line
where you want to start debugging. Then, from the Build menu, select Start Debug, and then Run to
Cursor. The yellow arrow will appear next to the statement selected.
Now press the F10 key. This causes the debugger to step to the next executable statement. The yellow
arrow will show where you are. Each press of F10 moves it to the next statement. If you’re in a loop, you’
Page 17

ABC Amber CHM Converter Trial version, />ll see the yellow arrow move down through the statements in the loop and then jump back to the top of the
loop.
Watching Variables
You’ll see a Watch window in the bottom right corner of your screen. To observe the values of variables
change as you step through the program, you’ll need to place these variable’s names in this Watch
window. To do this, right–click a variable name in the source code. A pop–up menu will appear. Select
QuickWatch from this menu. In the resulting QuickWatch dialog box, click Add Watch. The variable and
its current value will appear in the Watch window. If a variable is out of scope, such as before it’s been
defined, the Watch window will show an error message instead of a value next to the variable name.
Stepping Into Functions
If your program uses functions, you can step into them (single–step through the statements within the
function) by using the F11 key. By contrast, the F10 key steps over function calls (treats them as a single
statement). If you use F11 to trace into library routines like
cout <<
, you can trace through the source code
of the library routine. This can be a lengthy process, so avoid it unless you’re really interested. You need to
switch judiciously between F11 and F10, depending on whether you want to explore a particular function’
s inner workings or not.
Breakpoints
Breakpoints allow you to stop the program at any arbitrary location. Why are they useful? We’ve already
shown that you can execute the program up to the cursor location by selecting Run to Cursor. However,
there are times when you want to be able to stop the program in multiple locations. For example, you might
want to stop it after an
if
and also after the corresponding
else
. Breakpoints solve this problem because you
can insert as many as you need. (They also have advanced features we won’t describe here.)
Here’s how to insert a breakpoint in your listing. First, position the cursor on the line where you want the
breakpoint. Then click the right mouse button, and from the resulting menu select Insert/Remove

Breakpoint. You’ll see a red circle appear in the left margin. Now whenever you run your program at full
speed (by selecting Build/Start Debug/Go, for example) it will stop at the breakpoint. You can then
examine variables, single–step through the code, or run to another breakpoint.
To remove a breakpoint, right–click it and select Remove Breakpoint from the menu.
There are many other features of the Debugger, but what we’ve discussed here will get you started.
Previous
Table of Contents
Next
Page 18
ABC Amber CHM Converter Trial version, />Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore
ISBN: 157169160x
Publication Date: 11/25/98
Bottom of Form
Previous
Table of Contents
Next
APPENDIX D
BORLAND C++BUILDER
This appendix tells you how to use Borland C
++
Builder to create console-mode applications, which are the
kind of applications used in this book.
C
++
Builder is Borland’s most advanced development product, and, as of this writing, the C
++
product that
adheres most closely to Standard C

++
. It’s available in a student version for under $100. This discussion is
based on C
++
Builder 3.0.
We’ll assume that C
++
Builder is installed on your system, and that you can start it by using the Windows
Start button and navigating to the appropriate menu item: C
++
Builder.
You’ll want to make sure you can see file extensions (like .
CPP
) when operating C
++
Builder. In Windows
Explorer, make sure that the option Hide MS-DOS File Extensions for File Types That are Registered is
not checked.
Running the Example Programs in C++Builder
The programs in this book require minor modifications to run under C
++
Builder. Here’s a quick summary.
You can compile most of the example programs and run them without modification in Window’s MS-DOS
window (Start/Programs/MS-DOS Prompt). However, if you want to run them from within C
++
Builder,
using the Run command from the Run menu, then you’ll need to install a statement at the end of the
program to keep the console window on the screen long enough to see. You can do this in two steps:
• Insert the statement
getch()

; just before the final
return
statement in
main()
. This enables you to see
the program’s output.
• Insert the statement
#include &ltconio.h>
at the beginning of
main()
. This is necessary for
getch()
.
If you’re creating a multifile program, (as in Chapters 13, “Multifile Programs,” and 16, “Object-Oriented
Design”), insert the statement
#include &ltcondefs.h>
at the beginning of
main()
.
If the program you’re building uses Console Graphics Lite functions (described in Appendix E, “Console
Graphics Lite”), you’ll need to take some additional steps. These are summarized later in this appendix.
In the balance of this appendix we’ll cover these points in more detail and describe how to use C
++
Builder
to edit, compile, link and execute console-mode programs.
Cleaning up the Screen
When it’s first started, C
++
Builder shows you some screen objects you won’t need for console-mode
programs. You’ll see a window on the right called Form1. Click on its close button (the X in the

upper-right corner) to make it go away. Likewise, you won’t need the Object Inspector, so click its close
Page 19
ABC Amber CHM Converter Trial version, />button too. You’ll need to get rid of these two items every time you start C
++
Builder.
You may see a window titled
Unit1.CPP
. with a source file in it. This means C
++
Builder has started a
skeleton project for you. However, it’s not the kind of project you want, so click Close All on the File
menu to get rid of it.
You won’t need the Component Palette. This is a toolbar with tabs labeled Standard, Additional, Win32,
and so on. To get rid of it, click the Component Palette item near the bottom of the View menu. This
unchecks the item, so the palette will no longer be displayed. (If you want it back, you can check this item
again.)
If you need additional screen space, you can also turn off the standard toolbar. This toolbar contains
buttons for opening, saving, and other common tasks. All these tasks can also be accessed from the menu
bar, so if you don’t mind doing without the marginal convenience of the buttons, you can remove the
toolbar by clicking the Toolbar item near the bottom of the View menu.
Creating a New Project
C
++
Builder (as do other modern compilers) thinks in terms of projects when creating programs. A project
consists of one or more source files. It can also contain many other kinds of files which we don’t need to
be concerned with here, such as resource files and definition files. The result of a project is usually a single .
EXE
file that a user can execute.
To begin a new project, select New from the File menu. You’ll see a dialog box called New Items. Click
the New tab (if necessary). Then double-click the Console Wizard icon. In the resulting dialog box, make

sure that the Window Type is Console and the Execution Type is .
EXE
. Click Finish and you’ll see the
following source file appear in the Project Source window:
#pragma hdrstop
#include &ltcondefs.h>
//
#pragma argsused
int main(int argc, char **argv)
{
return 0;
}
This is a skeleton version of a console-mode program. You don’t need some of the lines in this program,
and you will need to add some others. We’ll make these changes, and add a statement to print some text
so you can see if the program works. Here’s the result:
//test1.cpp
//#include &ltcondefs.h> //not needed for one-file programs
#include &ltiostream>
#include &ltconio.h>
//#pragma hdrstop //not needed
//
//#pragma argsused //not needed
//int main(int argc, char **argv) //arguments not needed
int main()
{
cout << “Happy are they whose programs ”
<< “compile the first time.”;
getch();
Page 20
ABC Amber CHM Converter Trial version, /> return 0;

}
The
CONDEFS.H
file doesn’t need to be included (unless your program has more than one file), and the two
programs aren’t necessary. Also you don’t need the arguments to
main()
.
If you run the original skeleton program you’ll find that the console window doesn’t remain visible long
enough to see. As we noted, this can be fixed by inserting the statement
getch();
at the end of the program, just before
return
. This causes the program to wait for a keystroke, so the
console window remains in view until you press any key. The
getch()
function requires the
CONIO.H
header
file, so you’ll need to include it at the beginning of your program.
If you’re creating your own program, you can start with the skeleton program and type in your own lines.
If your starting with an existing file, read the section “Starting with Existing Files.”
Saving A Project
The text you see in the Project Source window is a source file, which has the extension .
CPP
. C
++
Builder
(as do other modern compilers) thinks in terms of a project, which can consist of (potentially) many such
source files. Information about a project is recorded in a file with the extension .
BPR

. Thus when you save a
project, you’re actually saving both the .
CPP
file (or files) and the .
BPR
file. When you first create it, the
project is called Project1 (or a higher number).
To save the project and change its name, select Save Project As from the File menu, navigate to the
directory where you want to store the file, type the name you want to give the project, followed by the .
BPR
extension, and click OK.
Starting with Existing Files
You may be starting a project with files that already exist, such as the ones in this book. If so, you’ll need a
little trick. You want the main file in your project, that is, the one containing
main()
, to have the same name
as the project. However, C
++
Builder will automatically create a file with this name, the skeleton file. It will
then try to override your file with the skeleton file when you try to save the project.
Here’s how to avoid the problem. Suppose your project is called
myProj
, and your main file is
myProj.cpp
.
Implement the following steps:
• Temporarily rename your main file (
myProj.cpp
) to a name other than the project name, say
XmyProj.cpp

.
• Use Save Project As to save your project. Give the project the same name as the original file,
but with the .
BPR
extension:
myProj.BPR
. Click Save. The skeleton file that was created,
myProj.cpp
,
will be saved as well.
• Close the project with Close All.
• Delete the skeleton file (
myProj.cpp
).
• Rename your source file (
XmyProj.cpp
) to the same name as the project (
myProj.cpp
).
Now when you open the project again (using Open Project from the File menu), your source file will be
the project’s source file as well. You can then modify it or compile it.
Compiling, Linking, and Executing
To build an executable program, select Make or Build from the Project menu. This causes your .
CPP
file to
Page 21
ABC Amber CHM Converter Trial version, />be compiled into an .
OBJ
file, and the .
OBJ

file to be linked (with various library files) into an .
EXE
file. For
example, if you’re compiling
MYPROG.CPP
, the result will be
MYPROG.EXE
. If there are compiler or linker
errors, they will be displayed. Edit your program until you’ve eliminated them.
Executing from C++Builder
If you’ve modified your program by inserting
getch()
as described earlier, then you can compile, link, and
run your program directly in C
++
Builder by simply selecting Run from the Run menu. If there are no errors,
the console window will appear, along with the output of the program.
Executing from MS-DOS
You can also run programs directly from MS-DOS. In Windows 95 and Windows 98, you can obtain a
box for MS-DOS by clicking the Start button, selecting Programs and then the MS-DOS Prompt item. In
the resulting window you’ll see what’s called the C-prompt: the letter C, usually followed by the name of
the current directory. You can navigate from one directory to another by typing cd (for Change Directory)
and the name of the new directory. To execute a program, including any of the examples from this book,
make sure you’re in the same directory as the appropriate .
EXE
file, and type the name of the program
(with no extension). You can find out more about MS-DOS using the Windows help system.
Precompiled Header Files
You can speed up compilation times dramatically by selecting Options from the Project menu, selecting the
Compiler tab, and clicking on Use Precompiled Headers. In a short program most of the compile time is

spent compiling the C
++
header files such as
iostream
. Using the Precompiled Headers option causes these
header files to be compiled only once, instead of each time you compile your program.
Closing and Opening Projects
When you’re done with a project, you can close it by selecting Close All from the File menu. To open a
previously-saved project, select Open Project from the File menu, navigate to the appropriate
.BPR
file,
and double-click it.
Adding a Header File to Your Project
Most C
++
programs employ one more user-written header file (in addition to many library header files,
like
IOSTREAM
and
CONIO.H
). Here’s how to create a header file.
Creating a New Header File
Select New from the File menu, make sure the New tab is selected, and double-click the Text icon. You
’ll see a source window titled
FILE1.TXT
. Type in the text of your file and save it using Save As on the File
menu, with an appropriate name, followed by the .
H
file extension. Save it in the same file as your source (.
CPP

) files. The new filename will appear on a tab next to the other files in the project. You can switch from
file to file by clicking the tabs.
Editing an Existing Header File
To open an existing header file, select Open from the File menu, and select Any File (*.*) from the Files
Of Type list. You can then select the header file from the list.
When you write the include statement for the header file in your
.CPP
file, make sure you enclose the
filename in quotes:
Page 22
ABC Amber CHM Converter Trial version, />#include “myHeader.h”
The quotes tell the compiler to look for the header file in the same directory as your source files.
Telling C++Builder the Header File’s Location
If you add a
.H
file, the compiler must know where to find it. If it’s in the same directory as your other files,
then you don’t need to do anything.
However, if your .
H
file is in a different directory, you’ll need to tell C
++
Builder where to find it. (This is
true of the
borlaCon.h
file necessary for console-mode graphics.) Go to Options on the Project menu and
select the Directories/Conditionals tab. In the Directories section, click the button with the three dots on
the right of the Include Path list. A Directories dialog box will appear.
In the bottom field of the Directories dialog box, type the complete pathname of the directory where the
.H
file is located. Click the Add button to place the path in the list of include paths. Then click OK twice more

to close the dialog boxes.
Don’t try to add header files to the project with the Add To Project option in the Project menu.
Projects with Multiple Source Files
Real applications, and some of the example programs in this book, require multiple source (.
CPP
) files.
Incidentally, in C
++
Builder, source files are often called units, a term specific to this product. In most C
++
development environments, files are called files or modules.
If you use more than one source file in your project, you’ll need to include the file
CONDEFS.H
:
#include &ltcondefs.h> //necessary for multifile programs
in the main source file; that is, the one containing
main()
. This is not necessary for one-file programs, as we
mentioned earlier, but is essential for multifile programs.
Creating Additional Source Files
You make additional .
CPP
files the same way you make header files: Select File/New, and double-click the
Text Icon in the New dialog box. Type in the source code, and use Save As to save the file. When using
Save As, make sure to select C
++
Builder Unit (.
CPP
) from the Save File As Type list. This will
automatically supply the .

CPP
extension, so all you need to type is the name. If you fail to do this, and
simply type the .
CPP
after the name, the file won’t be recognized as a C
++
Builder unit.
Adding Additional Source Files to your Project
You may have created a new additional source file as just described, or one may already exist, such as
BORLACON.CPP
, which is used for Console Graphics Lite programs. To add a source file to the project,
select Add To Project from the Project menu, navigate to the appropriate directory, and select the
filename from the list. Then click Open. That tells C
++
Builder it’s part of the project.
Multiple source files are displayed with tabs in the edit window (if they’re in full-size windows), so you can
quickly switch from one file to another. You can open and close these files individually so they don’t all
need to be on the screen at the same time.
The Project Manager
You can see what source files are part of the project by selecting Project Manager from the View menu.
Page 23
ABC Amber CHM Converter Trial version, />You’ll see a diagram of file relationships, similar to that shown in the Windows Explorer. Clicking the plus
sign next to the project icon will display all the project’s source files. The file you just added to the project
should be among them.
If you right-click a file in the Project Manager the context menu will show you choices that include Open,
Save, Save As, and Compile. This is a handy way to perform these tasks on individual source files.
In a multifile program you can compile individual files separately by selecting Compile Unit from the Project
menu. You can compile and link all the source files by selecting Make from the Project menu. This will
cause only those source files that have been changed since the previous compile to be recompiled.
Weird New Lines in Your Program

When you compile a multifile program, C
++
Builder automatically inserts lines into the source code of your
primary source file. These lines specify what the other source files are. For example, if you had a two-file
program consisting of
FILE1.CPP
and
FILE2.CPP
, you might see the following in
FILE1.CPP
:
//
USEUNIT(“file2.cpp”);
//
This is a permanent change to your source file. It’s not a very elegant approach to compiling multifile
programs, but at least you don’t have to add these lines yourself.
Console Graphics Lite Programs
Here’s how to build programs that use the Console Graphics Lite package. This includes such programs
as
CIRCSTRC
from Chapter 5, “Functions,” and
CIRCLES
in Chapter 6, “Objects and Classes.”
• Create a new project as described earlier, using the program name as the project name, but with
the .
BPR
extension.
• In the source file, change
#include&ltmsoftcon.h>
to

#include&ltborlacon.h>

• Tell the compiler where this
MSOFTCON.H
header file is by following the instructions in the
section earlier in this Appendix titled “Telling C
++
Builder the Header File’s Location.” (The header
should be in a directory called
BORLACON
.)
• Add the source file
BORLACON.CPP
to your project by following the instructions in the section
earlier in this Appendix titled “Adding Additional Source Files to your Project.”
• Insert the line
#include &ltcondefs.h>
at the beginning of your program. This is necessary for
multifile programs.
• To keep the display on the screen, insert the line
getch()
; just before the
return
statement at the
end of
main()
.
• To support
getch()
, insert the line

#include &ltconio.h>
at the beginning of your program.
Debugging
In Chapter 3, “Loops and Decisions,” we suggest using a debugger to provide an insight into how loops
work. Here’s how to do that with Visual C
++
. These same steps can help you debug your program if it
behaves incorrectly. We’ll be discussing one-file programs here, but the same approach applies, with
appropriate variations, to large multifile programs.
Start by building your program as you normally would. Fix any compiler and linker errors. Make sure your
program listing is displayed in the Edit window.
Single Stepping
Page 24
ABC Amber CHM Converter Trial version, />To start the debugger, just press the F8 key. The program will be recompiled, and the first line in the
program, usually the
main()
declarator, will be highlighted. Repeated presses of F8 will cause control to
move to each statement of the program in turn. When you enter a loop, you’ll see highlight move down
through the loop, then return to the top of the loop for the next cycle.
Watching Variables
To see how the values of variables change as you single step through the program, select Add Watch from
the Run menu. The Watch Properties dialog box will appear. Type the name of the variable you want to
watch into the Expression field of this dialog box, and click OK. A window called Watch List will appear.
By repeatedly using the Add Watch dialog box you can add as many variables as you want to the Watch
List.
If you position the Edit Window and the Watch List so you can see them both at the same time, you can
watch the value of the variables change as you single step through the program. If a variable is out of
scope, such as before it’s been defined, the Watch List will show an error message instead of a value next
to the variable name.
In the particular case of the

CUBELIST
program, the watch mechanism doesn’t recognize the validity of the
cube
variable when it’s defined within the loop. Rewrite the program so it’s defined before the loop; then its
value will be displayed properly on the Watch List.
Tracing Into Functions
If your program uses functions, you can trace into them (single-step through the statements within the
function) by using the F7 key. The F8 key steps over function calls (treats them as a single statement). If
you use F7 to trace into library routines like
cout <<
, you can trace through the source code of the library
routine. This can be a lengthy process, so avoid it unless you’re really interested. You will need to switch
judiciously between F7 and F8, depending on whether or not you want to explore a particular function’s
inner workings.
Breakpoints
Breakpoints allow you to stop the program at any arbitrary location. Why are they useful? We’ve already
shown that you can execute the program up to the cursor location by selecting Run to Cursor from the Run
menu. However, there are times when you want to be able to stop the program in multiple locations. For
example, you might want to stop it after an
if
and also after the corresponding
else
. Breakpoints solve this
problem because you can insert as many as you need. (They also have advanced features we won’t
describe here.)
Inserting a breakpoint in your listing is easy. Look at your program listing in the edit window. You’ll see a
dot in the left margin opposite each executable program line. Simply left-click the dot where you want to
insert the breakpoint. You’ll see a red circle appear in the left margin, and the program line will be
highlighted. Now whenever you run your program at full speed (by selecting Run from the Run menu, for
example) it will stop at the breakpoint. You can then examine variables, single-step through the code, or

run to another breakpoint.
To remove the breakpoint, left-click it again. It will vanish.
There are many other features of the Debugger, but what we’ve described here will get you started.
Page 25
ABC Amber CHM Converter Trial version, />

×