Вы находитесь на странице: 1из 838

C++ 21

Microsoft Visual C++.


.
,

Microsoft Visual Studio.


6.0 -
, MFC
, .
- .

.
,
.

21
1.
23
1.
24
2. C++
40
3.
51
4.
71
5.
100
6.
135
7.
167
2.
201
8.
202
9.
233
10.
264
11.
301
12.
333
13.
374
1 4.
41 3
3.
451
15.
452
16.
505
17.
544
18. - 561
19.
596
20.
644
21.
673
.
725

. C++
.
.

1



1.

C++


, -

C++ -
C++

C++ Java
ANSI





C++ HELLO.
Visual C++ 6

2. ++
C++
cout

727
728
736
807
21
21
21
23
23
23
24
24
24
25
25
26
28
29
29
29
30
30
31
31
32
33
33
36
36
37
37
38
38
38
39
40
40
42
44
44


: !

3.










typedef
short long



#deiine
const

4.

45
45
46
47
49
49
49
49
50
51
51
52
52
53
54
55
56
57
57
58
59
60
61
61
62
63
63
64
64
64
65
65
66
68
68
69
70
70
71
71
72
72
72







if

else
if
if







5.

,







;

,

74
74
74
75
77
77
78
80
80
81
82
83
86
86
88
90
92
93
93
93
93
94
95
95
97
97
98
98
98
100
1 00
1 01
101
1 02
1 02
1 04
1 06
1 06
108
1 09
11 0
111





,


inline-

6.








,
,


,



,
,
- const


, -

11 2
112
11 3
11 4
116
11 9
1 21
122
1 23
1 28
1 28
1 29
131
132
132
133
133
134
135
135
136
136
136
137
138
138
138
138
139
139
1 42
1 43
1 45
1 47
1 48
1 48
151
152
155
156
159

7.

goto
goto
while
while
break continue
while(true)
do...while
do...while
for
for
for

- for

switch
switch

2


8.




,

,

162
163
163
164
165
165
165
167
167
167
168
169
170
171
1 73
1 74
1 75
1 76
1 78
181
182
183
184
186
189
1 92
1 92
1 92
1 93
1 93
201
201
202
202
204
206
206
207
208
209
211
211

new
delete





this
,
const
const
-
const this

9.

(&)




swap()
swap()



247


,

,
!

?

212
213
215
215
216
217
218
221
222
225
226
227
228
230
231
231
231
231
233
233
234
236
237
239
239
241
242
243
244
246
250
253
255
256
257
259
261
261
262
262

10.
-
,
269
,


-





this









11.










262
263
264
264
266
269
269
271
272
276
277
278
280
281
283
284
284
286
288
290
290
290
291
293
296
297
298
299
299
299
301
301
302
303
303
305
307
309
313
315
317
319


,


-

12.
















strcpy() stmcpy()






13.

323
324
324
326
327
330
330
331
331
331
332
333
333
333
335
338
338
340
341
343
344
345
346
347
348
348
350
351
353
354
360
361
361
362
371
371
372
372
373
373
373
374
374


377

377

380

380
,
383

,
384


386

387

391

394
-
395

396

399

401

404

408

408
, 409
Java

41 0

41 0

411

411

411
14.
413
-
41 3
-
41 8

420

423

426

429
typedef
431
-
433
-
436

438

438

439

439

439
3

451


15.

16.

,
>> istream



ut

- ut
,
ut. width()


rintf()

ofstream

451
452
452
458
458
459
462
465
466
475
483
492
492
497
501
502
502
502
503
505
505
505
506
509
509
509
510
511
512
514
515
515
517
522
522
522
524
524
525
526
528
531
531


-
ofstream

-

17.








using
using
using


std

18. -

C++ - 561

:

532
532
533
536
538
541
541
542
542
543
544
544
545
548
549
550
550
550
551
553
553
555
557
557
558
559
560
560
560
561

562
563
565
566
567
567
568
569
570
573
574



CRC


19.








,




576
577
577
578
578
579
579
581
581
582
583
585
589
592
594
594
595
595
595
596
596
597
597
597
599
599
602
603
603
607
61 0
61 5
620
624
624
625
625
631
633
633
634
634
634

20.
, , ""

""


try catch

catch

658






21.


#define
#define
#define
#else

637
638
639
640
641
641
642
642
642
644
644
645
646
646
647
652
652
652
655
665
668
668
669
669
669
669
670
670
671
671
671
673
673
674
674
674
674
675
676
678
678
680


assert()
assert()
assert()





(AND)
(OR)
(OR)







switch





assert()
const

680
682
682
682
683
683
685
685
686
686
691
693
699
699
699
700
700
700
700
701
701
704
704
705
705
705
706
706
707
707
708
708
708
709
709
709
709
710
71 0
710
711
71 2
71 2

.
725
. C++
727
.
728
.
736

807

, 625
ASCII, 62; 732

, 626
, 101
, 631
, 539
, 626
, 113
, 626
, 323
, 266
, 452
, 429

, 610
, 732
, 47

, 633
, 731
, 466

ANSI, 548
iostream, 505
, 307
, 326
, 505
, 596; 624

, 731
#define, 674
, 699
#else, 675
, 701
#endif, 675
#ifdef, 674
, 506

#ifndef, 674
-
#include, 673
, 531
(#), 682
, 525
(##), 682
, 514
, 700
, 530

, 638
, 305
, 509
, 41 5
, 515
, 458
, 305
, 522
, 708
, 509
, 538
, 458
, 692
-, 483
, 517
, 603
, 511
3
, 524; 530
, 313


, 333

, 271
, 338
, 351
, 344

- , 505
Java, 409
, 646; 685
, 658
, 647
, 655
, 662
, 645
, 647
, 631

, 634
, 732

Animal, 599; 693


CAT, 273; 292; 342; 413
Counter, 276
deque, 633
Employee, 456
iostream, 510
list, 631
Mammal, 303
map, 634
ofstream, 531
ostream, 522
PartsCatalog, 465
Pegasus, 374
Rectangle, 264
String, 354; 452; 627; 687
Timer, 408
vector, 625
, 638
, 452

, 466

, 483
, 536
, 686
, 655
, 624
, 395
, 371; 597
, 677

, 650
, 677
, 708
-, 509
, 727
catch, 647
class, 303
const, 65; 709
enum, 66
inline, 122; 680
namespace, 548
new, 347
operator, 286
protected, 305
return, 11 4
static, 415; 548
template, 597
try, 647
typedef, 59; 431
using, 553
virtual, 322
, 57
, 44; 707

, 674
, , 674

, 64
#define,
65; 674
const, 65
, 66

, 64

, 64

, 307
, 327
, 269

, 309
, 272
, 269; 309
, 294
,
384
, 624
, 634
, 625
, 633
, 634
, 625
, 631
, 544
, 351; 512

, 327
, 272
, 272

, 674
DEBUG, 683

, 678
assert(), 683; 709
EVAL, 698
MAX, 678
MIN, 678
PRINT(x), 692
, 683
, 700

argv, 538
,
347
,
348

, 335
, 348
, 333
, 338; 344
, 343
, 333
, 341
, 340
, 351
,
350
, 346
, 436
, 426
, 598

, 377
, 375
, 317; 387

, 404
, 391
, 475
, 305
, 380
, 302
, 387
, 303; 466
, 303

, 110; 546
, 183

in, 510
ut;, 42; 522
ofstream, 531
-, 509
, 546
, 280
, 281
, 324
, 271

, 272
, 277
, 291
,
307
, 287
,
307
, 638

break, 171; 189


catch, 652
continue, 1 71
delete[], 350
dynamic_cast, 377
endl, 43
for, 1 77
goto, 1 67
return, 105; 114
switch, 186; 187; 705
using, 553
watch, 711
while, 1 69
, 725
(>>), 510
(::), 545
(<<), 497; 522
, 638
([]), 341; 342; 602;
626
(&), 358
, 358
, 286; 289
, 290
, 276; 290
, 699
, 296
, 725
(=), 291; 296; 602
, 289
, 286
(+), 286
, 280

, 290
,
317

,104
, 668

, 686
assert(), 685
, 693
, 634

, 1 29
, 1 29
, 52
, 1 29
, 47; 1 01
, 1 02
, 11 2
, 11 6

, 269
, 497
, 288; 359
, 284
, 278
, 11 9; 264

, 51
, 108; 129
, 54
, 51; 55
, 55; 58
, 1 06
, 51
, 61
, 52
, 413; 620
, 66
, 638
, 686
, 319

, 732
, 284

iostream, 510
ofstream, 531
ostream, 522
-, 509
, 526
, 284
, 673

HELLO.CPP, 40
, 44
, 683
, 704

Window, 548
, 550
, 550
, 557
, 544
, 548
, 557
std, 548; 558; 625
, 1 02

, 1 29
, 1 23

, 360
, 631
,
361
, 362
, 361
, 361

, 323
, 313
, 1 02

ASCII, 54; 62
, 44

, 669

, 63
, 43; 64
, 62
, 63
, 44; 64
, 530
, 728
, 730
, 729
, 732
, 631

STL, 624
, 129; 633
, 633
, 652
, 704
, 42; 351
, 351
, 358
, 359

, 323
, 47

char, 62 long, 60
short, 60
void, 47
(ADT), 396
(), 54
, 53
, 53
, 360
typedef, 59;
431
, 377
, 597
, 52; 57
, 294
, 669


ptr, 323; 436
rhs, 275
this, 283; 420
vptr, 323
, 130
, 433
, 348
, 420

, 676
, 536
-, 532
, 673
, 536
, 677
algorithm, 638
iomanip.h, 530
iostream.h, 43
list, 631
map, 634
stack, 633
stdio.h, 528
strin.h, 353
String.hpp, 458
vector, 625
, 1 02
, 1 02
, , 124; 184

, 699
, 701
, 700
, 700

stmcpy(), 353

bad(), 532
cin,get(), 515
cin.getline(), 518
cin.ignore(), 520
cin.peek(), 521

cin.putback(), 521
close(), 532
cout.fill, 525
cout.put(), 522
cout.setf 526
cout.width(), 524
cout.write(), 523
eof(), 532
fail(), 532
flush(), 522
Invariants(), 686
main(), 41; 100; 116
printf(), 528
sizeof(), 53
strcpy(), 353
strlen(), 359
, 47; 1 01
, 550
, 319; 662
, 1 01
, 1 00
, 492
, 603
, 313
, 46; 1 00
, 102
, 1 04
, 47
, , 1 01
, 11 9; 264
, 122; 680
, 11 9
, 1 00
, 1 02
, 1 02

315
, 61 5
, 418; 620
, 47

, 266
, 399


, 603
, 167
do...while, 175
for, 177
goto, 167
while, 169
, 189
, 182
, 181
, 596
Array, 597
, 599
, 607

, 599
, 597
, 598
, 597
, 602
, 620
, 597; 610

, 598; 610
, 333
, 340


(Jesse Liberty) , C++
- ,
C++ Report. Liberty Associates, Inc.
(http://www.libertyassociates.com),
Internet - ,
,
.
(Distinguished Software
Engineer at AT&T) -
(Citibank's Development Division).
(. ) (Stacey) (Robin)
(Rachel). Internet :
j liberty@nbertyassociates.com.
Web- : http://www.libertyassociates.com
Books and Resources ( ).


(David Levine) .


,
. ,
.
Sams,
. (Chris Denny)
(Brad Jones) .
(Tracy Dunkelbenjer),
(Holly Allender), (Sean Dixon), (Heather
Talbot), (Barbara Hacha) (Mona Brown).
, (Skip Gilbrech)
- (David McCune), ,
(Steve Rogers) (Stephen Zagieboyio),
C++. ,
:
(Gordon Anderson), (Richard Ascheri),
(Ron Barlow), (Ari Blachor), (Charles
Campuzano), (Tammy Cercone), (Michael
Chomiczewski), (. Raymond Church), (Charles
I. Desch), (Charles Dingman), (John Embow),
(Jay Erikson), (Mark Fiedler),
(Adam Fordyce), (Robert Francis),
(Christopher Gariepy), (Greg Gordon), (Charles
Hasegawa), (Elliot Kearsley), . (Andrew R. Kinnie),
(Lari Kirby), (Joe Korty), (Richard Lee),
(Roger Leininger), (Ruben Lopez),
(Ray Lush), (Frank Marrero), (Joan Mathew),
(James Mayhew), - (Sheryl McKenna),
(Judith Mills), (Terry Milner),
(Patrick Moore), (Chris Neely), (Gary Page),
(James Parsons), (Neeral Patel),
(Raoul van Prooijen), (Karen Risser), (Dan Rogers),
(Ralph Russo), (Gregory Safford),
(Joe Scalone), (Robert Sikes), (Sam Suboh),
(Walter Sun), (Paul Sutton), (James
Thompson), (Orlando Vanin), (Pascal Verdieu),
(Stephen Wain), (Jerry Wares),
(Jack White), (Scott Wilson), (Nick Witthaus),
(Michelle Zulli) (Donald Xie).
, (Mrs. Kalish),
1965 ( )
: , ,
.


++.
21 ,
-, , , - ,
++.
, .
,
.
.
,
,
.
, .


, ,
++, .
, , , ,
, ++.

.

++.


++ .


" "?
,
. ,
,


^

21


,
.


,
.

, ++
. ++
.
,
, .
. .
.
, ,
(
). ,
.

22


++
, .
++, ,
, ,
.
!
,
. ,
. ,
. ,
, ,
, , .


, , , .
,
,
. 6.


,
++ .

. 3 ,
, . 4
,
. 5 ,
, 6 . 7
,
- .

C++ 21 \
,
C++. :

C++
C++
, C++

C++

,
, .

, .
. ,
,
(, ADD MOV).
, BASIC COBOL.
,
, Let I = 100.
.
( )
. (
) .
. ,
.

24

,
, ,
.
, ,
. ,
.
, C++,
,
.
-.
(, Visual Basic)
. Java
(Virtual Machine, VM).
( Internet Explorer Netscape).

. ,
,
.
, (
) , .
,
.
. ,
, ,
.

:
( ), ,
.
, ,
: .
,
, .

.
, .
,
. ,
,
.
C++.


, , .

. , , , ,

1.

25

. .
,
. ,
, ,
.
,
, .
, (.. )
-,
, .. .
,
, , ,
, .
,
, .
Web
. ,
, .

, - ,
, .
,
.
,
-.

,
-
,
. , ,
, .
, ,
.
,
.

.
. , ,
,
, .

. . .
1.
2.
3.
4.

26

, .
.
.
.

.
1.
2.
3.
4.

.
.
.
.

,
.
1. .
2. .
3. .

. 1980-
.
-, (
, ) (, ..)
. , ,
, .
-, ,
. (
). ,
, . -
.
. , .
.

, .
,
.
(, )
.
, .
,
,
.

.
-
, ,

.
- ,
, ,
, .. , -
,
.

1.

27

C++ -
C++ -
, , : ,
.

,
, ( , )
. -
, ,
.
,
, .
. ,
.

,
-.
:
.
(.. ) , ,
.
C++
() , . ,
, 6.
, ..
.
. ,
; .


Acme Motors
, :
Star. , ,
.
, .. ,
Star, .
Quasar, Quasar
Star, .
C++ . ,
(), .
, ,
. Quasar Star,
, .
C++ 11 15.

28


Quasar, Star, -
. Quasar
Star.
.
, .
C++

. , , ,
. 10 13.

C++
- ,
, (Bjame Stroustrup) (
) ,
, - .
C++
C++,
C++ . C++
,
C++. , ,
C++,
, :
.


: C++ ,
? ,
C++, , ,
.

. ,
. 6,
- .

C++ u Java
C++ ,
.

, Java,
, , C++ Java,
.
, , 90% .

1.

29

ANSI
(Accredited Standards Committee),
(American
National Standards Institute ANSI), C++.
C++ ISO International
Standards Organization ( ). ,
C++, NCITS (National
Committee for Information Technology Standards
), ( NCITS),
ANSI/ISO. ANSI,
.
ANSI ".

ANSI , C++
(.. ). , ,
ANSI Microsoft,

. , ANSI, ,
Mac, Windows Alpha.
C++ ANSI .
ANSI
. ,
, , ANSI-.


C++, ,
, .
,
, . ,

, ,
, , ,
.
,
. , 90%
.
, , .
,
, : ?
, , ,
, .

30


:
, .. ? ,
,
- ?
, . ,
, :
.
,
, .

.
,
++ .


,
,
, Windows Macintosh. console easy window
, .
,
,
.
Windows Notepad, DOS Edit, Brief, Epsilon, EMACS
vi. , WordPerfect, Word
, .
, ,
. . , . . . ,
, . ,
, , .

C++ ,
, ,
^ .
:
. , .
C++.
.


, ,
, ( , ++),
, .
, .

1.

31




,
.

. , . . .

,

.

,

. -
,
.

, .

, , .
.
,obj.
.
.



++
( . o b j ) .
,
, ,
. ++
( ) , .
, ,
.
.
(. 5 6).
, ,
.
1. , .
2. obj
3. .
.

32


,
: ,
, . ,
( ) .
, ,
.
,
, ,
. . 1.1.

C++ - HELLO.cpp

Hello World - .
.
,
, , , ,
. Hello World.
, .
, .
.
.

. .
, 1.1 :
include <iostrean,h>

1.1. h e l l o , -
1: include <iostream.h>
2:

3:
4:
5:
6:
7:

int main()
{
cout "Hello World!\n";
return 0;
}

,
. .
5 .
<8>
. 5 (;).
!

1.

33

. 1.1. ++

, , .
, -
. - ,
,
. 1,
iostream.h (cannot find file iostream.h),

. ,
main, int main(); 3.
main ,
. main,
, .
:
1:
2:
3:
4:
5:
6:
7:

include <iostream.h>
int main(); //
int main()
{
cout << " Hello Wo rid !\n;
return 0;
}

HELL0.exe. ,
:
Hello world!


, ,
, ,
:
((include <iostream,h> .

((include dost)>
,
.
, 1
include <iostream>

using namespace std;

17.
, ,
, .

iostream (. 16).
. ,
, .

1.

35

, ,
.
: (# ) ---(
)-". 5 --'Hello world!'.

, ! ,
++. ,
,
.

Visual C++
Visual C++ 6.0
,
Microsoft Visual C++, 4.0
. , ANSI- ,
ANSI-
,

, .
, ,
, , ,
Microsoft. , -
. Microsoft Visual C++ 6.0,
.


, .
1. .
2. File New.
3. Win32 Console Application ( Win32),
, Example 1, .
4. An Empty Project ( ) .
5. File New.
6. C++ Source File ( C++) 1.
7. , .
8. Build Build Example1.exe.
9. .
10. <Ctrl+F5> .
11. .

36


.
.
, ,
.
!
, .
hello, 7.
, 1.2.
, ,
:
Hello,, line 5: Compound statement missing terminating; in function main(),

1.2. _______________________________________
1: include <iostream.h>
2:

3:
4:
5:
6:

int main()
{
cout << "Hello world!\n";
return 0;

:
F:\ \ Tycpp21d\ Testing\ ListOIOI.(8) : fatal error C1004:
unexpected end of file found
Error executing cl.exe.

}
,
( , ,
). ,
5.
, cout.
.
, .

, ,
C++, , .
, C++
, . C++
- ,
, C++
.

1.

37

, ,
++ , .
-
. .


?
, .

.
,
..
, ?

,
.
,
.
,
, ,
, .
, ?

,
, .

. ++
, , , , .
, .
?

, (
) (
). ,
, .


,
.
, .
,
.

1.
2.
3.
4.

38

?
?
?
?


, ,
.
include <iostream.h>
int main()

{
int x = 5;
int = 7;
cout "\n";
cout << x + << " " << x * ;
cout << "\n ";
return 0;

9
10:}

2. 1, .
? ?
3. .
?
include <iostream.h>
int main()

<
cout << "Hello World\n";
return 0;

}
4. 3, ,
. ?

1.

39


C++
++ , ,
.
, ,
, - .
:

++

C++
HELLO. , 1,
, .
. 2.1
HELLO. .

2.1. C++ h e l l o ,
1: include <iostream.h>
2:

3: int main()

4: {
5: cout << "Hello World!\ n";
6: return 0;

7: >

Hello World!

40

1 iostream. h .
#,
. .
, , (#),
, . V 21.
Include ,
: .
. ,
, , ,
. ,
, iostream.h ,
. h, . iostream. h (mput-outputstream -) cout,
>. 1 iostream. h
, *
,
(), .
3 main().
C++ main(). ,
.
, nain() :
.
main(), ,
. HELLO. main()
int ( integer ), ,
.
0, 6.
, -
, C++ , main()
( ).

main()
, void.
C++, .
main() int
return 0;.


, .
0 .

({)
(>). ()
4 7. ,
, .

2. C++

41

5.
cout .
6, cout
16. , cout, C++
(, ) (, ).
cout: cout,
( ).
, , .
, ("),
5.
.
(\) , Hello
world! .
cout 17.
main() 7.

cout
16 , cout
. , cout, ,
cout, (<<),
(<). ,
C++ .

2.2. c o u t _______________________________________________
1: // 2.2. cout
2: include ciostream.h>
3: int main()
4: {
5: cout << "Hello there.\ n";
6: cout << "Here is 5: " << 5 << \ n";
7: cout "The manipulator endl writes a new line to the screen.";
8: cout <<
9:
endl:
10: cout << "Here is a very big number:\ t" 70000 << endl;
11: cout << "Here is the sum of 8 and 5:\ t" << 8+5 << endl;
12: cout << "Here's a fraction:\ t\ t" << (float) 5/8 << endl;
13: cout << "And a very very big number:\ t";
14: cout << (double) 7000 * 7000 <<
15:
endl;
16: cout << "Don't forget to replace Jesse Liberty with your name...\ n";
17: cout << "Jesse Liberty is a C++ programmer!\ n";
18: return 0;
19: }

42

. cout
2.2. , ,
: Jesse Liberty ,
.
Hello there.
Here is 5: 5
The manipulator endl writes a new line to the screen.
Here is a very big number: 70000
Here is the sum of 8 and 5: 13
Here's a fraction:
0.625
And a very very big number: 4.9e+07
Dont forget to replace Jesse Liberty with your name...
Jesse Liberty is a C++ programmer!

,
cout
. 11
:
11: cout << "Here is the sum of 8 and 5:\ t" << (8+5) << endl;

2 include <iostream.h>
iostream.h .
iostream.h , cout
-.
5 cout:
. \ ,
cout
( - ).
6 cout ,
. "Here is 5: .
: .
cout 5,
( ).

Here is 5: 5

,
. .
7 ,
endl. .
( endl 16.)
endl end line ( )
"-", "-" ( / ).

2. C++

43

10 \t,
,
( 10-13). 10
long int. 11 , cout
. cout ,
8+5, 13.
12 cout 5/8.
(float) cout,
. 14 cout 7000 * 7000,
(double) .
double float
3.
16 .
,
, . !

, , .
, ,
, , , ,
.

, . ,
,
.


++ : (//)
(/). (
++) ,
.
( )
, ( / * )
, :
(*/) /*
*/.
, ,
,
.
++
,
. ,

.

44



, ,
.
, ,
. ,
.
,
, - , .
,
?
, .
.
2.3 , ,
.

2.3. h e l l o , _______________
1: include <iostream.h>
2:

3: int main()
4: {
5: /* ,
6: ,
7: */
8: cout << "Hello world!\ n";
9: //
10: cout << "That comment ended!\ n";
11:

12: // ,
13: /* , , */
14: return 0:
15: }

Hello world!
That comment ended!

5-7 ,
9, 12 13. 9
, , 5 13,
(*/).

: !
, , .
,
. . ,

2. C++

45

, .

.
, , ,
.

main(), , ,
. ,
. main() ,
.

, - .
.
, .
. ,
, .
, .
, ,
,
, . 2.4.

2.4. ________________________________________________
1:

include <iostream.h>

2:

3:
// DemonstrationFunction
4://
5:
void DemonstrationFunction()
6:

7:
8:

cout << "In DemonstrationFunction\ n";


}

9:
10:// main ,
11:// DemonstrationFunction
12:// .
13:
int main()
14:
{
15:
cout "In main\ n" ;
16:
DemonstrationFunction();
17:
cout << " Back in main\ n";
18:
return 0;
19:
>

In main
In DemonstrationFunction
Back in main

46

58 01:1:1().
.
1() 13, 15
, ,
( ) . 16
^^^). ,
01().
, 7, .
^^) ( 8)
, .
17, ( )
.


, void,
.. . ,
,
. , , ,
void.
.
, .
. ,
, .
:
int Sum(int , int b)

, .
, , .
.
. , ,
.

( ),
.
.
(return). .
,
void. , ,
, .
5;
, , 3. ,
, ,
,
,
.

2. C++

47

2.5 ,
.
(, int ):
3.

Z.5. [ f u n c . ] _______________________
1:
include <iostream.h>
2:
int Add (int x, int y)
3:
{
4:
5:cout << "In Add(), received " << x << " and " << << "\ n";
6:
return (x+y);
7:
}
8:
9:
int main()
10 :

11:
cout << "Im in main()!\ n";
12:
int a, b, c;
13:
cout << "Enter two numbers:
14:
cin >> a;
15:
cin >> b;
16:
cout << "\ nCalling Add()\ n";
17:
c=Add(a,b);
18: cout << "\ nBack in main().\ n";
19:
cout << "c was set to " << c;
20: cout << "\ nExiting...\ n\ n;
21:
- return 0;
22:

>

I'm in main()!
Enter two numbers: 3 5
Calling Add()
In Add(), received 3 and 5
Back in main().
was set to 8
Exiting. , .
Add () 2.
....... .
9, .
( 1315). ,
, , <Enter>. 17 mai()
Add() , .
Add (),
2. b , .
6, .

48


, ,
: ,
.
C++. ,
.


include?
,
. ,
, .
// /*?
, (//),
. , (/*),
, (*/) ,
,
(/*). (*/),
.
?
,
, .
, .
, ,
.


,
.
, .
,
.


1. ?
2.
3.
4.
5.

mainO?
?
?
?

2. C++

49

1. , I love C++.
2. , ,
.
3. : . ?
?
1:
2:
3:
4:
5:

include <iostream.h>
int main()
{
cout << Is there a bug here?";
return 0;

6: }

4. 3, ,
.

50


.

. :


++ .
,
, .
.
. .
, .

100

101

102

103

104

105

106

. 3.1.
(, \/1)
, , , .
. 3.1 . ,
103. ,
\/1 .

3.

51

.
.
. ,
.


C++
, int, chart .
,
.
.
, , ..
(, int) , (
) .

, .
.



,
.
char ( )
.
char.
, .
character, ,
, .

short int ( )
, long int ( ) , int
( short long) .
(16- 32-)
. ' 32- ,
(, Visual C++ 4 ),
.
4- , . ,
3.1,
.
, ,
.

52

3.1.
include <iostream.h>
2:

3: int main()
4: {
5:
cout << "The size
6: cout " The size
7;
cout << " The size
8
cout << " The size
9
cout
' Thesize
cout
' Thosize
10
11
cout
' Thesize

of
of
of
of
of
of
of

an
a
a
a
a
a
a

int is:\t\t" sizeof(int) " bytes.\n";


short int is:\t\t" sizeof(short) " bytes.\n"
long int is:\t\t" sizeof(long) " bytes.\n";
char is:\t\t" sizeof(char) " bytes,\n";
float is:\t\t" << sizeof(float) " bytes.\n";
double is:\t\t" sizeof(double) " bytes.\n";
bool is:\t\t" sizeof(bool) " bytes.\n";

12

13
14

return 0;

The
The
The
The
The
The
The

size
size
size
size
size
size
size

of
of
of
of
of
of
of

an int is:
a short int is:
a long int is:
a char is:
a float is:
a double, is:
a bool is:

4
2
4
1
4
4
1

bytes.
bytes.
bytes.
bytes.
bytes.
bytes,
bytes.

3.1 . ,
sizeof() 5-10.
sizeof() ,
, .
, 5 sizeofO int.
int .
int long int .


, ,
.
. (short long)
unsigned .
. .
,
, , ,

3.

53

,
. unsigned short int
065 535. , ,
, ,
- 32 76832 767. - ,
.


C++ .
( ), ( )
.
,
.
256 ASCII, ASCII.
ASCII ,
. ASCII American Standard Code for Information Interchange (
).
ASCII,
.
, C++,
. 3.1.
, .
, 3.1, . 3.1.

3.1.
Jan

bool

true false

unsigned short int

0-65 535

short int

-32 768-32 767

unsigned long int

0 - 4 294 967 295

long int

-2 147 483 648-2 147 483 647

int (16 )

-32 768-32 767

int (32 )

-2 147 483 648-2 147 483 647

unsigned int (16 )

0-65 535

unsigned int (32 )

0-4 294 967 295

char

256

float

1,2-38-3,438

double

2,2-308-1,8308

54

,
. 3.1.
, , ,
3.1, , . 3.1
.
, ,
,
.


, , (
) ,
.
, , : , J23qrsnf myAge.
, ,
.
myAge:
int myAge;

()
. ,
,
,
, , .
, ( ,
).


, J23qrsnf, (, i)
, .
, myAge howMany.
, ,
.
.
, , .
1:
int main()

{
unsigned short x;
unsigned short y;
unsigned short z;
z = x * y;
return 0;

3.

55

2:
int main ()

{
unsigned

short

unsigned

short

Length;

unsigned

short

Area;

Area

Width

Width;

Length;

return 0;

,
, .
, .

, ,
, ,
, ,
.


C++ . ,
. , AGE
.


. ,

.


. , ,

.

. (, ),
_
. ,
.
,
(_) . ,
.
: , 111<\* .. ,
, ,
.

56


. ,
, . ,
( int)
/, ( long int) /.
,
, .
, C++,
, ,
( . 6), ,
C++ .


C++
.
. if, while,
for main.
. C++
.


.

.-'
, ++
.
,


.


.

.


C++
. ,
, . :
unsigned int myAge, myWeight; // unsigned int
long int area, width, length; // long int

, myAge myWeight,
. area, width
length. (long),
.

3.

57


(=). ,
5 Width, :
unsigned short Width;
Width = 5;

long long
short int.

int,

a short

Width

unsigned short Width = 5;

,
. , , ,
,
.
, .
,
. :
// long
long width = 5, length = 7;

width long int


length 7.
, :
5,

int myAge = 39, yourAge, hisAge = 40;

int,
.
3.2 , .
, .

3.2. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1:

//

2:

include <iostream.h>

3:
4:

int main()

5:

6:

unsigned short int Width = 5, Length;

7:

Length = 10;

8:
9:

// Area unsigned short

10: // Width Length

58

11

unsigned short int Area = (Width * Length);

12
<< Width << "\n";

13

cout

'Width:

14

cout

'Length : " Length << endl;

15

cout

'Area:

16

return 0

17

Area << endl;

Width: 5
Length: 10
Area: 50

2 include,
'
iostream,
cout. , 4.
6 Width unsigned
short int, 5.
Length ,
. 7 Length 10.
11 Area unsigned short int,
,
Width Length. 1315
. ,
endl.

typcdef
,
unsigned short int. ( ,
.) C++
typedef, .
(
6). ,
typedef, ,
. ,
typedef unsigned short int USHORT;

USH0RT, ,
unsigned short int. 3.3 3.2
USH0RT unsigned short int.

3.3. t y p e d e f __________________________________
I I *****************
2: // typedef
3: include <iostream.h>
4:

3.

59

5; typedef unsigned short int USHORT; //

6:
7: int main()

8: {
9: USHORT Width = 5;
10: USHORT Length;
11; Length = 10;
12; USHORT Area = Width * Length;
13: cout "Width:" Width "\n";
14: oout "Length: " Length endi; .
15; cout "Area: " Area << endl;
16: return 0;
17: }

Width : 5
Length: 10
Area: 50

5 USHORT typedef
unsigned short int.
, 3.2,
.


short long
,
long,
short. ; ,
,
.
. 3.1 unsigned short int, ,
, , , 65 535.
,
, .
unsigned long int
(4 294 967 295), - .
, float double,
. float double
,
7 19 , .. .
.
, ,
. int,
.

60


,
?
,
,
. 3.4 ,
short.

3.4. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: ((include ciostrean,h>
2: int nain()
3: {
4: unsigned short int smallNumber;
5: smallNumber = 65535;
6: cout "small number:" smallNumber endl;
7: smallNumber++;
8: cout "small number:" smallNumber << endl;
9; smallNumber++;
10; oout "small number:" smallNumber endl;
11: return 0;
12:}

small number:65535
small number:0
small number;1

4 smallNumber unsigned short int,


,
0 65 535. 5 smallNumber
, 6 .
7 smallNumber 1.
, (++).
, smallNumber 65 536.
unsigned short int , 65 535,
0, 8.
9 smallNumber ,
.


,
.
.
3.5 , ,
, short int.

3.

61

3.5.
1: #include <iostream.h>

int main()

short int smallNumber;

smallNumber = 32767;

cout << "small number:'

smallNumber++;

cout << "small number:'

smallNumber++;

10: cout << "small number:'

smallNumber

endl;

smallNumber

endl ;

<< smallNumber

<< endl;

11 : return 0;
12: }

small

number:32767

small

number:-32768

small number:-32767

4 smallNumber
(short int) (
unsigned , .. ,
).
, , .
, , ,
.
,
(
), .

( char) ,
256 (. ).
char 0255, ASCII.
ASCII ISO (International Standards Organization
)
, .
, ASCII 97.
,
1 128. 128
, IBM
- .
ASCII ".

62

,
. .

.
,
1, 0.
,
, , ,
.


- , , char,
, 0 255.
,
ASCII .
,
97.
( , ) ,
. , 5
5 . 5
53, 97.

.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: #include <iostream.h>
2: int main()
3: {
4: for (int i = 32; i<128; i++)
5: cout << (char) i;
6: return 0;
7: }

7; ' ! "#$% ()*+, . /0123456789:; <>?@ABCDEFGHIJKLMN0P


_QRSTUVWXYZ[\]" 'abcdefghijklftinopqrstuvwxyz{ | {-

, 32127.


C++ ,
. (
. 3.2.) ,
( ), ,
. ,
, , ,
t :
char tabCharacter = '\t';

3.

63

char ( tabCharacter),
\t,
.
, (, ).
,
. , ,
(\),
.

3.2. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

V
\?
\\

, ,
. , ,
( ).
, ,
C++ : .


,
. ,
int myAge = 39;

int,
39.
myAge

39


, ( ,
). , ,
.
students,
classes,
, ,
(, 15 ):
students = classes * 15;

64

* .

15 .
,
:
students = classes * studentsPerClass

,
,
studentsPerClass, ,
.
C++ .

define.

#define
:
define studentsPerClass 15

, studentsPerClass
(int, char ..). define
. , studentsPerClass,
15.
,
, 15.

const
define , C++
, :
const unsigned short int studentsPerClass = 15;


unsigned short int.
,
.
( define)
,
(.. ).
studentsPerClass,

.
, ,
^^,
.

3.

65

,
.

, .
short long,

.


,
, .
, COLOR
: RED, BLUE, GREEN, WHITE BLACK.
enum,
: , , ,
, . :
enum COLOR { RED, BLUE, GREEN, WHITE, BLACK };

.
1. COLOR, .
2. : RED 0;
GREEN 2 ..

BLUE

1;


. 0,
, .
,
,
, . ,
enum Color { RED=100, BLUE, GREEN=500, WHITE, BLACK=700 };

red 100; blue 101; GREEN


500; WHITE 501; BLACK 700.
COLOR,
( RED, BLUE, GREEN, WHITE
BLACK 100, 101, 500, 501 700). COLOR
.
, ,

. ,
unsigned int
. ,
.
3.7 , .

66

3.7.
1: include <iostream.h>
2: int main()
3: {
4: enum Days { Sunday, Monday, Tuesday,
5: Wednesday, Thursday, Friday, Saturday };
6: int choice;
7: cout << "Enter a day (0-6): ";
8: cin choice;
9: if (choice = Sunday || choice == Saturday)
10: cout "\nYoure already off on weekends!\n;
11: else
12: cout "\nOkay, I'll put in the vacation day.\n";
13: return 0;
14: }

Enter a day (0-6): 6

Youre already off on weekends!

4 DAYS
. ,
; , (Tuesday) 2.
0 6.
Sunday,
. ,
, 9.
. ,
, 3.8.

,
,
. ,
,

. ,

.

3.8. ,
1:

include <iostream.h>

2:

int main()

3:

4:

const int Sunday = 0;

5:
6:
7:

const int Monday = 1;


const int Tuesday

= 2;

const int Wednesday = 3;

3.

67

8:

const int Thursday = 4;

9:

const int Friday = 5;

10:

const int Saturday = 6:

11:
12:

int choice;

13:

cout << "Enter a day (0-6): ";

14:

cin << choice;

15:
16:

if (choice = Sunday || choice == Saturday)

17:

cout << "\nYou re already off on weekends!\n";

18:

else

19:

cout "\n0kay, I'll put in the vacation day.\n";

20:
21:

return 0;

22:

"}

I
r

' Enter a day (0-6): 6


' ' Youre already off on weekends!


3.7. (Sunday, Monday .)
Days. ,
.

,
C++ .
(char, short long int),
(float double). , (unsigned).
,
.
.
, .
, , ,
, .
, ,
, :
define const.


short int
, long int?

(short), (long)
, long int,
. , unsigned short int

68

65 535, unsigned long int


4 294 967 295.

( ), , 100
200 . ,
,
( ) .
, ,
f l o a t , ?
int aNumber = 5.4;

,
.
. , 5,4 ,
5. ,

float, 5.
?

,

. ,
. ,
360,
degreesInACircle ( ), , .
, ?

:
unsigned int aPositiveNumber = -1;

,
.
. , -1 11111111 11111111 (OxFF
) 65 535. -
, .
C + + ,
?

, . C++ ,
, ,
. C++
. , ,
, .


,
.
, .
,
.

3.

69


1. ( )
?
2. unsigned short int long int?
3. ?
4. const
define?

5. ?
6. (enum) , Blue?
enum COLOR { WHITE, BLACK = 100, RED, BLUE, GREEN =300 };

7. ,
?
)
) !
)

R79J

Totallncome

Invalid

1. ?
.
.
.
.
2. .
3. pi, 3.14159.
4. float , pi.

70


,
. ,
, , .
.
:






++

++
, (
). ++ .
.
:
= + ;

, , +.
:
, +.

,
. (=) ,
, , ,
.

4.

71


, ,
, .
:
=+;

+ b ;

, .
,
.
. C++
, , .

.



, .
({) (}).
,
, :
<
temp = ;
= ;
b = temp;

}
,
.


,
.

.


,
, .

, , ++
. , . , 3+2;

5. .

72

, ,
. :
3.2

// 3.2

// , 3.14

8111^ // , 60

, 1 , 3.14, ):1:
, .

, 60,

= + ;

,
, .. .
.
:
= = + ;

.
.
+ .
= + .
, , 2,
5, 7.
4.1.

4.1. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1

include <iostream.h>
int main()

2
3

int a=0,

cout <<

cout <<

b=0
"a:
x:

a = 9;

b = 7;

= x =

a+b;

10:

cout <<

"a:

11:

cout

12:

return 0

13:

x:

x=0, y=35
a "

b:

x '

a "

y:

b:

" x

y:

b;
"

b;
"

: 0 : 0 :

0 : 35

: 9 : 7 :

16 : 16

4.

73

4 .
5 6. 7
9. 8 7. 9
b , .
= +b, , .

,
. . C++
, . C++ :

;
.


(=) ,
, ,
. ,
= + ;

,
.
, ,
, 1- ( . left, .. ). ,
,
, - ( . right, .. ).
r-
,
. , :
= 35; //

:
35 = ; // !

: 1- ,
, - ,
. , 1- -, -
1-. -, 1-
, . , : = 5;, : 5
= ; ( 1- -, 5 -).


C++ : (+), (-),
(*), (/) (%).
:
. ,

74

,
.
. 4.2 ,
.

4.2. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: // 4.2.
2: //
3: include <iostream.h>
4:
5: int main()

6: {
7: unsigned int difference;
8: unsigned int bigNumber = 100;
9: unsigned int smallNumber = 50;
10; difference = bigNumber - smallNumber;
11: cout << "Difference is: " << difference;
12: difference smallNumber - bigNumber;
13: cout << "\nNow difference is: " difference endl;
14: return 0;
15: }

IRrlf: Difference is: 50


Now difference is: 4294967246

^
10,
* "'
11, . 12
,
. ,
( ) , ,
. .


.
, , .
21 4 (21/4)
5 1.
, 21 4 (21 % 4),
1.
, ,
. ,
10 , , ..
10 . , 1 % 10 1; 2 % 10 2 ..;
10 % 10 0. 11 % 10 1; 12 % 10 2;
, 10, 20.
7.

4.

75


5 3 1. ?

. , 5/3 1.
.
5,0 / 3,0 : 1,66667.
,
float.
,
. : " , ".
, ,
: " , : ".
: " ,
, , : .
.
ANSI static_cast.
4.3.

llucmuHg 4.3. npuBegewue nepeMEHHoB k

myna f l o a t

1: include ciostream.h>

2:
3: void intDiv(int x, int y)
4:

<

5: int z = x / y;
6: cout << "z: " << z << endl;
7: }

8:
9: void floatDiv(int x, int y)

10: {
11: float a = (float)x;

//

12: float b = static_cast<float>(y)

//

13: float c = a / b;
14:
15: cout << c: " << c << endl;
16:}
17:
18: int main()
19: {
20: int x = 5, y = 3;
21: intDiv(x.y);
22: floatDiv(x,y);
23: return 0;
24: }

76

z: 1
: 1.66667

20 . 21
101, 22
floatDiv. 9. 11 12
float.
float 13
15.



, ,
. myAge
, :
int myAge = 5;
int temp;
temp = myAge +2; // 5 + 2 temp
myAge = temp;

// myAge

. C++
,
:
myAge = myAge + 2;

, C++
: myAge
myAge.
, :
+= 2;

(+=) - 1-,
1-.
4,
6.

(-=), (/=), (*=) (%=).


( ) .
++ 1 , 1
. .

4.

77

(++) 1,
(--) 1. ,
, :
C++;

//

:
= + 1;

, , .
+= 1;


, :
.
(++), (++).
,

.
, .
: ,
. : ,
.
,
. ,
5, , ,
int = ++;

(
6), . ,
6 6.
,
int b = ++;

b
(6), .
b 6, 7.
4.4
.

4.4. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: // 4.4.
2: //
3: //
4: include ciostream.h>
5: int main()

6: {
7:

78

int

myAge

39;

//

8:

int yourAge = 39;

9;

cout << "I am: " myAge << " years old.\ n";

10:

cout << "You are: " yourAge " years old\ n";

11:

myAge++;

12:

++yourAge; //

13:

cout << "One year passes.. n";

//

14:

cout << "I am: " myAge " years old.\ n";

15:

cout << "You are: " yourAge << " years old\ n";

16:

cout << "Another year passes\ n";

17:

cout << "I am: " << myAge++ " years old.\ n";

18:

cout << "You are: " << ++yourAge " years old\ n";

19:

cout << "Let's print it again.\ n";

20:

cout << "I am: " << myAge << " years old.\ n";

21:

cout << "You are: " << yourAge " years old\ n";

22:

return 0;

23: }

I
You
One
I
You

am

are

You

am
are

years

39

year
am

Another
I

39

are

years

old
old

passes

40
40
year
40
41

years
years

old
old

passes
years
years

old
old

Lets print it again


I

am

41

years

old

You are 41 years old

IT ; 7 8
'
39.
9 10.
11 myAge
, 12 yourAge
. 14 15;
, ( 40 ).
17 myAge (
),
. ,
, 40.
( ) 18
yourAge .
,
41.
, 20 21 .
, myAge 41,
yourAge ( :
!).

4.

79



, , :
= 5 + 3 * 8:
, 8 * 8 , 64.
, 5 + 24, 29.
(
). , ,
29.
,
. ,
= 5 + 3 + 8*9 + 6 * 4 ;
, : 8*9 = 72 6*4 = 24.
:
= 5 + 3 + 72 + 24;
, : 5 + 3 = 8; 8 + 72 = 80; 80 + 24 = 104.

. , !
, ?
:
^ = 111 + * 60
,
^ 60,
^. ,
, 60,
.
,
, . ,
, ,
.
:
(1515 = (^ + 11) * 60



. ,
, ,
:
115081 = ( ( (^ + ) * 60) *
(PeopleInThe0ffice + 10\/1::1) )

80

.
^ ,
.
60. PeopleInTheOffi.ce
10\/. ,
.
.
, ,
, .
:
^ = ^ + ^;
^^^ = ^ * 60;
111 = PeopleInTheOffice + 10\/1:1;
1 = 11 * ^;


, . ,
, 60
.
.

(++)


.

(++)


.

,
.


,

.

[ ';:' ':


C++
, ANSI
bool, : true false.

. , ,
false ,
true.

4.

81

bool,
long int
, . ANSI-
bool.



. true () false
(). . 4.1.

ANSI bool,
bool true false.
C++ 0
false ( 1) true.

myAge 39,
yourAge 40, , (==),
, :
myAge == yourAge; // myAge yourAge?

0,
.

false

(),

myAge > yourAge; // myAge yourAge?

0 ( false).

++
(=) (==).
,
.

++ : (==),
(<), (>), (<=), (>=) (!=).
. 4.1 ,
.

true false.

(=)
(==).

++
!

82

4.1.

tB3Bpa%aeMee anaieHBe

==

100 == 50;

false

50 == 50;

true

100 ! = 50;

true

50 != 50;

false

100 > 50;

true

50 > 50;

false

100 >= 50;

true

50 >= 50;

true

100 < 50;

false

50 < 50;

false

100 <= 50;

false

50 <= 50;

true

>

>=

<

<=

if
, . if
(, )
, , .
if :
if ()

',

,
. false,
. true,
. :
if (bigNumber > smallNumber)
bigNumber = smallNumber;

bigNumber smallNumber.
bigNumber ,
smallNumber.
, ,
, if
, :
if ()

{
1;

4.

83

2\
;

}
:
if (bigNumber > smallNumber)

{
bigNumber = smallNumber;
cout << "bigNumber: " << bigNumber << "\ n";
cout << "smallNumber: " << smallNumber "\ n";

}
, bigNumber

, .
4.5 ,
.
smallNumber,

4.5. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: // 4.5.
2: // if
3: include <iostream.h>
4: int mainO
5: {
6: int RedSoxScore, YankeesScore;
7: cout << "Enter the score for the Red Sox:
8: ein >> RedSoxScore;
9:
10: cout << "\ nEnter the score for the Yankees: ";
11: ein >> YankeesScore;

12:
13: cout "\ n";
14:
15: if (RedSoxScore > YankeesScore)
16:

cout << "Go Sox!\ n";

17:
18: if (RedSoxScore < YankeesScore)
19: {
20: cout << "Go Yankees!\ n";
21:

cout << "Happy days in New York!\ n";

22:}
23:
24: if (RedSoxScore == YankeesScore)
25: {
26: cout "A tie? Naah, cant be.\ n";
27: cout "Give me the real score for the Yanks: ";
28: ein >> YankeesScore;
29:
30: if (RedSoxScore > YankeesScore)

84

31:

cout "Knew it! Go Sox!";

32:
33: if (YankeesScore > RedSoxScore)
34:

cout "Knew it! Go Yanks!";

35:
36: if (YankeesScore == RedSoxScore)
37:

cout << "Wow, it really was a tie!";

38; }
39:
40: cout << "\ nThanks for telling me.\ n";
41: return 0;
42: }

' Enter the score for the Red Sox: 10


Enter the score for the Yankees: 10
A tie? Naah, can1t be
Give me the real score for the Yanks: 8
Knew it! Go Sox!
Thanks for telling me..

I,


.
. if 15, 18 24.



1^8\/1 < 10);
\/1 = 10;


\/1 10 , ,
, , ..
\/1 10.
,
5\/1 ( )
10. ? ,
, ,
, .
, .
-:
if(SomeValue < 10) //
; // , if
\/1 = 10; //


if
.

4.

85

,
. ,
, 25 38.
-,
.
: Yankees
Red Sox, if 15 false 16
. 18 (true)
20 21. if 24
; (false) (
, 18 true).
39.
if
if.


, 4.4
if. ,
, .
, .

,
, ,
if:
if (){

>

:

if,

if ()

<

>
, :
if ()

, ,
.

else
,
(.. true)
, (.. false)

86

. 4.4
, (RedSoxScore > Yankees) true,
, false.

if , .

else ( 4.6):
if ()

;
else

4.. e l s e ____________________________________
1:

// 4.6.

2:

// if else

3:

include <iostream.h>

4:

int main()

5:

6:

int firstNumber, secondNumber;

7:

cout << "Please enter a big number:

8:

ein >> firstNumber;

9:

cout \ nPlease enter a smaller number: ";

10:

ein secondNumber;

11:

if (firstNumber > secondNumber)

12:

cout << "\ nThanks!\ n";

13:

eise

14:

cout << "\ nOops. The second is bigger!";

15:
16:

return 0;

17:

Please enter a big number: 10


Please enter a smaller number: 12
Oops. The second is bigger!

11 , if.
, 12,
16. false,
14. 13 else,
14 ,
. if-else if,
else.
, if-else
, , .

4.

87

if
i .
1:
if ()

<

;
;

true, ,
false, ,
.
, ,
.
.

2:
if ()

'

2;
;

true, !,
2. .
:

:-:

':

- cout "SomeValue is loss than 10"):

elseSjiI";;;.
cout "SomeValue is not less than

''-'''''

.;:':

CQUtt^

if

if-else, if else.
if:
if ( 1)

{
if (2)
1;

else
{
if ()

2\

else
;

}
}
else
4;

88

if :
") 2 , -!.
, 2 , , , 2. , 2 , . , , ,
if !
if
4.7.

4.7. if_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: // 4.7.
2: // if
3: include <iostream.h>
4: int main()

5: {
6:

//

7:

// bigNumber littleNumber

8:

// bigNumber littleNumber,

9:

// ,

10:

// , ,

11:
12:

int firstNumber, secondNumber;

13:

cout << "Enter two numbers.\ nFirst:

14:

cin >> firstNumber;

15:

cout << "\ nSecond: ";

16:

cin >> secondNumber;

17:

cout "\ n\ n";

18:
19:

if (firstNumber >= secondNumber)

20:

21:

if ( (firstNumber % secondNumber) == 0) // evenly divisible?

22:

23:

if (firstNumber == secondNumber)

24:

cout << "They are the same!\ n";

25:

else

26:

cout "They are evenly divisible!\ n";

27:

28:

else

29:

cout << "They are not evenly divisible! \ n";

30:

31:

else

32:

cout << "Hey! The second one is larger!\ n";

33:

return 0;

34: }

Enter two numbers.


First: 10

4.

89

Second: 2
They are evenly divisible!
:"

( ),
. if ( 19) , .
, else, 31.
true, ,
20, if 21
, (.. ,
). ,
, . if 23
, ,
.
if 21 false,
else 28.


if
1^
.
:
if ( > )

//

if ( < ) // ,
= ; //


, if
.
, ,
.
, else if,
. 4.8.

4.8.
e l s e i f ____________________________________________________________________
1:

// 4.8.

2:

// if

3:

include <iostream.h>

4:

int main()

5:

6:

int x;

7:

cout << "Enter a number less than 10 or greater than 100:

8:

ein >> x;

9:

cout "\ n";

90

10
11

if ( >=

12

if ( >

13

10)
100)

cout << "More than 100, Thanks!\ n";

14

else

15

// if

cout

"Less than 10, Thanks!\ n";

16
return 0

17
18

Enter a number less than 10 or greater than 100: 20


Less than 10, Thanks!

10 100
,
.
if, 11, true,
( 12). 12 ,
10. 12 if,
true, 100.
100, 13.
10, if 11 false.
else ( 15),
. ,
10, .
, else 14
if 11. else if
12, , .
C++
. - . ,
,
. 100
.
4.9 ,
.

4.9.
1 if
1

// 4.9.
// if

include ciostream.h>

int main()

int x:

cout << "Enter a number less than 10 or greater than 100:

cout << "\ n";

cin >> x;

10:

4.

91

11: if (x >= 10)


12: {

13: if (x > 100)


14:

cout << "More than 100, Thanks!\

n";

15: }
16: else
17:

// !
cout << "Less than 10, Thanks!\ n";

18: return 0;
19: }

Enter a number less than 10 or greater than 100: 20

, 12 15, ,
---------- , , else 16
if, 11, .
20, if 11
true; if 13 false,
. ,
else 14, ,
.

, ,
, .
;
,
.



, . , , ,
2? , ,
, .
,
.
, ,
. C++. . 4.2.

4.2.
/

&&

1 && 2

II
]

1 || 2

92


,
true, true. , ,
, , , ,
- . ,
if ( ( == 5) && ( == 5) )
true, 5.
false, 5.
, true , .
&&. &
, 21.


.
, true.
, .
: , .
( ). ,
if ( (X == 5) II ( == 5) )

true, ,
, 5.
: 11.
, |, ,
21.


true,
( false). ,
, false! ,
if ( !( == 5) )

true , 5.
-:
if ( != 5)


, :
if ( ( == 5) && ( == 5) )

( == 5) ,
false (.. 5), ( ==
5), ,
.

4.

93

,
if ( ( == 5) ( == 5) )

( == 5),
{ == 5),
, .



C++ true false. ,
(. ),
.
,
if ( > 5 && > 5 || 2 > 5)

. ,
, true, 5
z 5. , , ,
true , 5 , 5.
3, z 10,
true (z 5,
),
: false ( true, ,
5,
&& ,
).
,

,
, :
if ( ( > 5) && ( > 5 | | z > 5) )


false. , ( 3) 5,
false, ,
false. , true ,
true. ,
, ,
.

, .
, ,
, .

94


C++ false,
true. ,

if. ,
if () // ,
= 0;

'

: ,
.
, :
if ( != 0) //
= 0;

, .
. , -
, .
:
if (!)

// ,

if ( == 0) //

, ,
.

,

.

1^)
1^ ! = 0).
,
.
!)
^( == 0).
,
.


(?:) C++,
.
:
(1) ? (2) : ()

: 1 true,
2, .
.

4.

95

4.10 if.

4.1.
1:// 4.10.

2:

//

3:

include <iostream.h>

4:

int main()

5:

6:

int x, , z;

7:cout << "Enter two numbers.\ n";


8:

cout << "First:

9:

cin >> x;

10: cout << "\ nSecond:


11: cin >> y;
12: cout << "\ n";
13:
14:

if (x > y)

15:

z = x;

16:

else

17:

z = y;

18:
19:

cout <<^'z: " << z;

20:

cout << "\ n";

21:
22:

z = (x > y) ? x : y;

23:
24:

cout "z: " z;

25:

cout << "\ n";

26:

return 0;

27:

Enter two numbers.


First: 5
Second: 8
z: 8
z: 8

: , .
. 14
if, , ,
.
19.
22
. : ,
; .

96

. 24.
, , ,
if.. .else.

. ,
C++,
C++ if.
, ,
, .
,
if .

. ,
, .
,
,
, .


,
?

, ,
. , ,
, , ,
.
true false,
(true)?

true false,
,
. :
if ( ( = + ) == 35 )
C++.
,
35. , ,
.
,
?

, (
) ,
.
?

, ( , ),
.

4.

97



,
.
, .
,
.


1. ?

2. = 5 + 7 ? ?
3. 201 / 4?
4. 201

% 4?

5.

myAge,
:

int,

myAge = 39;

myAge++;

b = ++;

6. 8+2*3?
7. if( = 3) if( == 3)?
8. true false?
)

-1

= 0

== 0 // , 0

1.

if,
,
else.
2. . , .
?
1:

include <iostream.h>

2:

int main()

3:

4:

int a, b, c;

5:cout << "Please enter three numbers\ n";

98

6:

cout << "a: ";

7:

ein >> a;

8:

cout << "\ nb:

9:

cin b;

10

cout << "\ nc:

11

cin >> c;

12
13

if (c = (a-b))

14

{ cout "a:

15

cout a;

16

cout "minus b:

17

cout b;

18

cout << "equals c:

19

cout << c endl; >

20

else

21

cout << "a-b does not equal c:

22

return 0;

23

" << endl

3.

2; ,
. 20, 10 50. ,
? ?
4. :
1: include <iostream.h>
2: int main()
3: {
4: int a = 1, = 1, ;
5: if ( = (a-b))
6: cout << "The value of is: " << c;
7: return 0;
8: }

5.

, ,
4. ? ?

4.

99


-
, ,
. , :


,
. ++
,
. 1() , , ,
..
, ,
, .
( ).
, .
. 5.1.

. ,
,
.
: ()
.
-.
.

100

Program

. 5.1. ,
,

,

,
.
,
. ,
. ,
int myFunction();
, myFunction .
.
.
int myFunction(int someValue, float someFloat);

, myFunction ,
: .
,
. , , .
int theValueReturned = myFunction(5, 6. 7);

theValueReturned ,
myFunction,
5 6,7. .


,
, .
, . -

5.

101

, .
, .
.

, #111,
.

, .

, .
.


,
.
-,
.
-, , ()
( ) , , ()
( ) . ()
() () , ..
.
-, .
,
,
,
, ,
.


,
<11. , ,

.

unsigned short int FindArea (int length, int width);


. 5.2.
,
, .
.
(} ,
. . 5.2.

102


. ,
. ,
. , ,
, :
long Area(int, int);

,
long .
, .
. ,
, :
long Area(int length, int width);

, .
,
. , int.
, , main(),
. 5.1
, ( ).

5.1. , _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: // 5.1.
2: int
3: include <iostream.h>
4: int Area(int length, int width); //
5:
6: int main()
7: {
8: int lengthOfYard;
9: int widthOfYard;
10: int areaOfYard;

11

12: cout << "\ nHow wide is your yard? ";


13: >> widthOfYard;
14: cout << "\ nHow long is your yard? ";
15: ein >> lengthOfYard;
16:
17: area0fYard= Area(length0fYard,widthOfYard);
18:
19: cout << "\ nYour yard is ";
20: cout << areaOfYard;
21: cout << " square feet\ n\ n";
22:

return 0;

23: }
24:
25: int Area(int yardLengtlr, int yardWidth)
26: {
27:

return yardlength * yardWidth;

28: }

5.

103

How wide is your yard? 100


How long is your yard? 200
Your yard is 20000 square feet

i Area() 4.
>>***
, 25.
, ,
. ,
. ,
.
, length
width : yardLength yardWidth.
, ;
.

; .

, . ()
widthOfYard, lengthOfYard,
widthOfYard
yardLength,

lengthOfYard yardWidth.
, , .


.
,
.

Area

(Int length, int width)

^
// Statements
return (length * width);
\ \

J

. 5.3.

,
. . 5.3.

104


:
_ _ ([ [_]..

'.

.-;-.;/:'-

: :

'b'"

' V--

,
. , -
, .
. (; ).

. ,
.
,
, .
,
return. ,
.
.
, int.
.
, void.

:
long FindArea(long length/ long width); // long, .
void PrintMessage(int messageNumber); // void,
ih% GrCho i ) ;f: :// pa int,
BadFunctionO; // int,

:
long FindArea(long 1, long w)
return 1 * w;

void PrintMessage(int whichMsg)

{
if (whichMsg == 0)
cout "Hello.\n": ,
: / 'if (whihMsg == 1)
cout "Soccbye.\n":
if (whichMsg > 1)..;'

'

"I'm confused.\n"; '

'

5.

105


,
({).
, if (
7).
( ).


,
. ,
, .
,
.
.
, , ,
. 5.2
,
.

5.Z. u _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1:

include <iostream.h>

2:
3:

float Convert(float);

4:

int main()

5:

6:

float TempFer;

7:

float TempCel;

8:
9:cout << "Please enter the temperature in Fahrenheit:
10:

ein >> TempFer;

11:

TempCel = Convert(TempFer);

12:cout << "\ nHeres the temperature in Celsius: ";


13:

cout << TempCel << endl;

14:

return 0;

15:

>

16:
17:

float Convert(float TempFer)

18:

19:

float TempCel;

20:

TempCel = ((TempFer - 32) * 5) / 9;

21:

return TempCel;

22:

106

Please enter the temperature in Fahrenheit: 212


Here's the temperature in Celsius: 100
Please enter the temperature in Fahrenheit: 32
Here's the temperature in Celsius: 0
Please enter the temperature in Fahrenheit: 85
Here's the temperature in Celsius: 29.4444

6 7 float: (TempFer)
,
(TempCel) . 9
, Convert().
Convert()
, 19,
, TempCel. ,
TempCel, 7.
Convert(). ,
TempFer, main()
.
Convert() FerTemp
CelTemp, . ,
.
TempCel ,
: 32 TempFer,
5 9.
, 11
TempCel main(). 13
.
.
212, , (212)
(100).
. ,
.

, .
.
,
. ,
, ,
. , ,
,
.
.
,
.
7.

5.

107

1:

include <iostream.h>

2:
3:

float Convert(float);

4:

int main()

5:

6:

float TempFer;

7:

float TempCel;

8:
9:

cout << "Please enter the temperature in Fahrenheit:

10:

ein >> TempFer;

11:

TempCel = Convert(TempFer);

12:

cout << "\ nHere's the temperature in Celsius: ";

13:

cout << TempCel << endl;

14:

return 0;

15:

16:
17:

float Convert(float Fer)

18:

19:

float Cel;

20:

Cel = ((Fer - 32) * 5) / 9;

21 :

return Cel ;

22:


, ,
.


, - ,
, main().
,
, .
. ,
,
, . 5.3.

5.3. _ _ _ _ _ _ _ _ _ _ _ _ _
1 :
2:

include <iostream.h>
void myFunctionO; //

3:
4:

int x = 5, = 7; //

5:

int main()

6:

7:
8:

cout << " from main: " << x << "\ n";

9:

cout << "y from main: " << y << "\ n\ n";

10:

myFunctionO;

11:

cout << "Back from myFunction!\ n\ n";

108

12: cout "x from main: " x "\ n";


13: cout << "y from main: " << y << "\ n";
14: return 0;
15: }
16:
17: void myFunction()
18: {
19: int y = 10;

20:
21: cout << "x from myFunction: " << x << "\ n";
22: cout << "y from myFunction: " y << "\ n\ n";
23: }

x from main: 5
from main: 7
x from myFunction: 5
from myFunction; 10
Back from myFunction!
x from main: 5
from main: 7

,
,
. 4
. 5,
7.
8 9 main() .
, main(),
, .
10 myFunction()
18, 19 ,
10. 21 myFunctionO .
, main(). 22
,
.

main(),
. ,
myFunction().

:
, C++
. C++ ,
,

5.

109

. ,
,
.

,
. ,
.
14
, ++, .


, , ,
. , ,
, .
++ ,
. ,
. , ,
, ,
, , 5.4.

5.4.
1

// 5.4. ,

//

3
4

include

<iostream.h>

void

myFuncO;

7
8

int main()

10

int x = 5;

11
12

cout << "\ nln main x is: " << x;

13

myFunc();

14
15

cout << "\ nBack in main, x is: " << x;

16

return 0;

17
18
19

void

20

myFuncO

21
22

int X = 8;

23

cout << "\ nln myFunc, local x: " << x << endl;

24
25
26

cout << "\ nln block in myFunc, x is: " << x;

27

110

28: int x = 9;
29:
30
31

cout << "\ nVery local x: " << x;

>

32
33

cout << "\ nOut of block, in myFunc, x: " << x << endl;

34: }

In main x is: 5
In myFunc, local x: 8
In block in myFunc, x is: 8
Very local x: 9
Out of block, in myFunc, x: 8
Back in main, x is: 5


main() ( 10). 11
, 5.
MyFuncO, 22
8.
23.
, , 25, 26
. 28
,
. 9.
30.
31, , 28,
.
33 ,
22.
28, - 8.
34 MyFuncO
.
15, , 10.
,
, MyFuncO.
,
, !

,
, ,
.
, ;
main() C++.
, (
, ).

5.

111

++ , ,
.
, ,
. , ,
, :
, .
, .
, , ,
.


.
, , ,
int, long .
C++,
, ,
.



, ,
.
, doublet), triple(),
square() cube(), .
:
Answer = (double(triple(square(cube(myVal)))));

myValue
(), ( )
square(). squareO
( ), , triplet).
triplet) ( )
doublet). , doublet) ( )
Answer.
,
( ?); ,
.

:
unsigned long myValue = 2;
unsigned long cubed = cube(myValue);

/ / 2

= 8

unsigned long squared = square(cubed);

/ / 8

= 64

unsigned long tripled = triple(squared);

// 64 * 3 = 192

unsigned long Answer = double(tripled);

// 192 *2 = 384

,
.

112

-
, , .
, , ,
.
, .. .
,
. 5.5.

5.5.
// 5.5.
/(include <iostream.h>
void swap(int x, int );
int main()

{
int x = 5, = 10;
cout << "Main, Before swap, x: " << x << " : " << << "\ n"
swap(x,y);
cout << "Main. After swap, x: " << x << " : " << << "\ n";
return 0;

>
void swap (int x, int y)

<
int temp;
cout "Swap. Before swap, x; " << x << " : " << << "\ n"
temp = x;
x = y;
= temp;
cout << "Swap. After swap, x: " << x << " : " << << "\ n";

ESSS

Main,

Before

swap,

Swap.

Before

swap,

Swap.

After

Main.

After swap,

swap,

10
10

10

5 :

10

' I 1(),
"
swap(), , ,
.
() , .

5.

113

9,
11. swap(),
.
swap(), 21
, . ,
. 2325
, 27.
,
swap().
13,
main(), ,
, , !
, swap()
, .. swap() ,
. ,
2325, ,
, main().
8 10
, main().


, void,
, .
, return,
, .
, , :
return 5;
return ( > 5);
return (MyFunction());


, , MyFunctionO
. , return ( > 5), false, 5,
true, 5. ,
, , false true
( ).
return,
, ,
. return
, ,
, return, .
return.
5.6.

114

1,

5.6. r e t u r n
1: // 5.6.
2: // return

3:
4: include <iostream.h>
5:
6: int Doubler(int AmountToDouble);
7:
8: int main()
9: {
10 :
11: int result = 0;
12: int input;
13:
14: cout << "Enter a number between 0 and 10,000 to double: ";
15: cin >> input;
16:
17: cout << "\ nBefore doubler is called... ";
18: cout \ ninput: " input " doubled: " result << "\ n";
19:
20: result = Doubler(input);

21:
22: cout << "\ nBack from Doubler...\ n";
23: cout << "\ ninput: " << input << " doubled: " << result << "\ n";
24:
25:
26: return 0;
27: }
28:
29: int Doubler(int original)
30: {
31: if (original <= 10000)
32:

return original * 2;

33: else
34:

return -1;

35: cout << "You cant get here!\ n";


36: >

Enter a number between 0 and 10,000 to double: 9000


Before doubler is called...
input: 9000 doubled: 0
Back from doubler...
input: 9000 doubled: 18000
Enter a number between 0 and 10,000 to double: 11000
Before doubler is called...
input: 11000 doubled: 0
Back from doubler...
input: 11000 doubled: -1

5.

115

14 15 input. 18
result. 20
Doubler() .
result, 23
.
31, DoublerO,
10 . , 10 ,
. 10 ,
-1 .
35 ,
( 10 000 )
32, 34, 35.
,
, !


int main() void maln()
? ,
int maln(){ return 0;}?
, int
mainO ANSI-, , int main()
.
, . int
main() .
, ,
.
, ANSI
.

,
, ,
.
. ,
long myFunction(int);

.
,
.
, ,
. ,
,
. :
long myFunction (int = 50);

116

. myFunction
long int.
, 50.
,
-:
long myFunction (int = 50);

,
.
-:
long myFunction (int )

,
50. ,
, ,
: , , , .

. : -
,
.
,
long myFunction (int Paraml, int Param2, int );

Param2 ,
. Paraml
,
Param2, . ,
, 5.7.

5.7. ,
// 5.7.
//
include <iostream.h>
int VolumeCube(int length, int width = 25, int height = 1);
int main()

{
int length = 100;
int width = 50;
int height = 2;
int volume;
volume = VolumeCube(length, width, height);
cout "First volume equals: " volume "\ n";
volume = VolumeCube(length, width);
cout << "Second time volume equals: " << volume << "\ n";

5,

117

21: volume = VolumeCube(length);


22: cout << "Third time volume equals: " << volume "\ n;
23: return 0;
24: >
25:
26: VolumeCube(int length, int width, int height)
27: {
28:
29: return (length * width * height);
30: }

: First volume equals: 10000

geconcj time volume equals: 5000


Third time volume equals: 2500

VolumeCube()B 6 ,
, ,
.
___

. , 25,
1. , ,
.
.
1012 ,
, .
VolumeCube() 15.
16.
18 VolumeCubeO ,
.
, , 19.
VolumeCubeO ( 21)
, . ,
, 22.
1

,
,
.

118



,

.
, ,
,
,
.
, ,

,
.


C++
. .
:
, ,
. :
int myFunction (int, int);
int myFunction (long, long);
int myFunction (long);

myFunctionO .
, .

. ,
,
, .
. (. poly)
, (rp. morphe) , ..
, .

, .
,
. ,
.
, , , ,
double
Averagelnts(), AverageDoubles() ..
, ,
.
int, long, float double.
:
int Doubleint(int);
long DoubleLong(long);
float DoubleFloat(float);
double DoubleDouble(double);

:
int Double(int);
long Double(long);
float Double(float);
double Double(double);


, .
,
. 5.8.

5.

119

5.8.
I:

// 5.8.

2:

//

3:
4:

include <iostream.h>

5:
6:
7:

int Double(int);
long Double(long);

8:
9:

float Double(float);
double Double(double);

10:
II :

int main()

12:
13:
14:

int mylnt = 6500;


long myLong = 65000;

15:
16:
17:
18:
19:

float myFloat = 6.5F;


double myDouble = 6.5e20;

20:
21:

float doubledFloat;
double doubledDouble;

22:
23:
24:

cout << "mylnt: " mylnt << "\ n";


cout "myLong: " << myLong "\ n";

25:

cout "myFloat: " myFloat "\ n";

int doubledint;
long doubledLong;

26:cout << "myDouble: " << myDouble << "\ n";


27:
28:
29:

doubledint = Double(mylnt);
doubledLong = Double(myLong);

30:

doubledFloat = Double(myFloat);

31:
doubledDouble = Double(myDouble);
32:
33:cout "doubledint: " doubledint "\ n";
34:cout << "doubledLong: " << doubledLong << "\ n";
35:cout "doubledFloat: " doubledFloat "\ n";
36:cout << "doubledDouble: " << doubledDouble << "\ n";
37:
38:
return 0;
39:

40:
41:

int Double(int original)

42:
43:

{
cout "In Double(int)\ n";

44:

return 2 * original;

45:
46:
47:

}
long Double(long original)

48:

<

49:

cout "In Double(long)\ n";

120

50: return 2 * original;


51: }
52:
53: float Double(float original)
54: {
55: cout << "In Double(float)\ n";
56: return 2 * original;
57: >
58:
59: double Double(double original)
60: {
61: cout << "In Double(double)\ n";
62: return 2 * original;
63; }

mylnt:
myLong:

6500
65000

nyFloat: 6.5
myDouble:
6.5e+20
In Double(int)
In Double(long)
In Double(float)
In

Double(double)

Doubledint:
DoubledLong;
DoubledFloat:

13000
130000
13

DoubledDouble: 1.3e+21

jsf**'i * , DoubleO :
'
int, long, float double. 69,
41-63.
.
1316 , 2831

Double(). ,
. :
!
, ,
DoubleO.

.


,
,
. ,
,

5.

121

- . ,
,
.

inline-

.
,
, .
10 ,
. , , 10.
, ,
. , , (..
- ), ,

.
,
.
inline (.. ),
,
.
.
,
. 10 ,
10 .
,
.
?
, - ,
. ,
.
5.9.

5.9. inline-

__________

// 5.9. inline-
include <iostream.h>
inline int Double(int);
int main()

{
int target;
cout << "Enter a number to work with:
cin target;
cout "\ n";
target = Oouble(target);

122

16: cout << "Target: " << target endl;


17:
18: target = Oouble(target);
19: cout << "Target: " << target endl;

20:
21:
22: target = Double(target);
23: cout << "Target: " << target << endl;
24: return 0;
25: }
26:
27: int Double(int target)
28: {
29: return 2*target;
30: }

Enter a number to work with: 20


Target:

40

Target:

80

Target: 160

5 DoubleQ,
int int.
,
inline.

target = 2 * target;

Double():
target = Double(target);

inline
.

.

. ,
. ,
. ,
, .
.
,
, .

5.

123

( ) :
,
. ,
( , - ).
, , ,
.
,
, (()
, ,
5.4.
,
:
1,1,2,3,5,8,13,21,34...

( )
. , , , 12-
.

. 1.
. ,
. - (-2)- (-1)-
, > 2.
.
,
, .
< 3.
:
1. , .
2.

1(),
, .

3.

() (). < 3,
1; 1() (),
-2, ,
-1, .

(1), 1. (2),
1. (3), ,
1(2) (1). ^13(2) 1
(1) 1, (3) 2.
1(4), ,
(3) 1^13(2). , ^()
2 ( (2) 1(1)) 1^(2)
1, 1^(4) 3,
.
. (5), ,
14(4) (3). , 1=].(4)
3, (3) 2,
5.

124

(
(20) ! 1 () 13 529 !),
. .
, . ()
. .
,
.
1() 5.10.

, 5.10,
( 15).
,
.

5.10.
include <iostream.h>
int fib (int n);
int main()

{
int n, answer;
cout << "Enter number to find: 10: cin >> n;
cout << "\ n\ n";
answer = fib(n):
cout << answer << " is the '' << n << "th Fibonacci number\ n"; 17: return 0;

}
int fib (int n)

{
cout << "Processing fib(" << n << ")... 23:
if (n < 3 )

{
cout << "Return 1!\ n":
return (1);

}
else

{
cout << "Call fib(" << n-2 << ") and fib(" << n-1 << ").\ n";
return( fib(n-2) + fib(n-1)):

>
}

5.

125

Enter number to find: 6

Processing

fib(6).. . Call fib(4)

and f b (5)

Processing

fib(4).. . Call fib(2)

and fib(3)

Processing

fib(2).. . Return 1!

Processing

f b (3).. .Call fib(1)

Processing

fib(1).. . Return 1!
f b (2).. .Return 1!

Processing

and f b (2)

Processing

f b (5).. .Call fib(3)

and f b (4)

Processing

fib(3).. , Call fib(1)

and f b (2)

Processing

fib(1).. . Return 1!

Processing

fib(2).. . Return 1!

Processing

f b (4).. .Call fib(2)

Processing

fib(2).. . Return 1!

Processing

fib(3).. . Call fib(1)

Processing

fib(1).. . Return 1!

Processing

f b (2).. .Return 1!

and f b (3)
and f b (2)

8 is the 6th Fibonacci number



28,
, 28 :

( cout.

28: cout << "Call fib(" << (n-2) << ") and fib(" << n-1 << ").\ n";

9
. ()
. ^(), 20
.
21 , 3, , ,
() 1. ,
^() -2 -1. ,
^(),
,
. , ,
^(1) (2). ()
. 5.4 5.5.
, , 6,
() (6).
(), 30
3. 6 3, (6)
, (4) ^(5):
38: 1( (-2) + ^(-1));

, (4) (5) (
6, ^(-2) , (4), (-1)
, (5)). (6), -

126

, , . ,
.

/ return 1 /

7 L 7 / retum1 / /return1 /

__________ ^-----------------------------------'fibi
return 1

/W. 5.4.

. 5.5.

5.

127

1(5) ,
3, 1() , 4 3.
(4) , , (3) (2).
,
5.10, . ,
, 1, 2, 3, 6,
.

. 20,
1(),
().
++ ,
.

.
,
,
.

-
.
, ,
.
( , void)
.
? ,
?
? , ?
? ,
?
,

. ,
.



. , ,
. ,
, . ,
,
. .
, .
,
, . ,
, ,
. , ,
.

128

, .
,
,
.


,
(, DOS Microsoft Windows)
. C++,
, , ,
.
.
,
, .
,
, (Central Processing
Unit CPU).
, .
- ,
.
( ) .
, .
,
, .
,
.
, . . 5.6.

100

X
II

101 Int =7;

102 Cout ;
103 Func (,);
104 =9;
105 return;

. 5.6.
,
, .
, "
(. 5.7).
, ,
, .
: , , (
). ,
. 10 1 ,
, , .

5.

129

,
. ,
, .
.

. 5. 7.

.
, .
, .
,
( ).
,
. , , .
, , , . 5.8.


theVariable

80

MyAge

50

YourAge

37

' 102!
/

. 5.8.

,
, ,
.

130

,
.
. 5.9.

theVariable

MyAge

YourAge

. 5.9.


,
DOS, .
1.

, ,
, .
.

2.


.
int, ,
.
3. ,
, .
.

4.

,
. , ,
, .

5. , .
6.

,
, .. .

7. .
, ,
2.
,
, .

5.

131

,
, , , 1,
. ,
,
, .

,
.
:
.
.

, .

.
,
. C++
main(), , , .
,
, .
( inline).
,
.

, .
.
.
, ,
, . ,
,
.


?
- .
,
, ,
. ,
( )
.
inline?
( - )

, , , inline.

132

, ,
, ?
, ..
.
.
, , , ,
?
8.
,
.
, :
int Area (int width, int length = 1); int Area (int size);

? ,
, |^.
, , Area ()
, ,
Area(int, int) Area(int).


,
.
, .
,
, .


1. ?
2. , ,
?
3. , *?
4. ,

?
5. ?
6. ?
7. ?
8. ?
9. ?
10. ?

5.

133


1.

Perimeter,
unsigned long int unsigned short int.

2.

Perimeter 1.
,
( ).

3. : ?
include <iostream.h>
void myFunc(unsigned short int x);
int main()

{
unsigned short int x, y;
= myFunc(int);
cout << "x: " << x << y: '' << "\ n";

}
void myFunc(unsigned short int x)

{
return (4*x);

>
4. : ?
include <iostream.h>
int myFunc(unsigned short int x);
int main()

{
unsigned short int x, y;
= myFunc(x);
cout << "x: " x << " : " << << "\ n";

}
int myFunc(unsigned short int x);

{
return (4*x);

}
5.

, unsigned short int


.
, ,
-1.

6.

,
, 5.
, , -1.

7.

, .
,
, .. 2,
4, 16.

134


C++,
, .
:

- -


,
. . ,
Height Width (unsigned short int),
065 535,
. ,
, . ,
,
.
Height Width ,
.
, :

, ;

, .

. , ,
, , .. C++
,
.

6.

135

!
,
.
,
,
,
. ,
, ,
, , .
, .


.
( ),
.
-, ,
, , , .. , ,
, , ,
, ..
,
.
, ,
. ,
, .
, .. , ,
, , .
,
. - . -, ,
, ..
-, -,
. - ,
.
-.
- .
Start() Break(). Cat -,
,
SleepO, Meow() ChaseMice().
- , -.
- .


class,
, - .
. ,
, Cat:

136

class Cat

<
unsigned int itsAge;
unsigned int itsWeight;
void Meow();

Cat .
Cat, , (itsAge
itsWeight), , ( MeowO). ,
Cat, ..
Cat.
, Cat
( itsAge itsWeight). MeowO
.


, - . 3,
. , Cat (), Rectangle ()
Employe () , a Meow( ) (),
ChaseMiceO
() StopEngineO ()
, , .
- its (, itsAge,
itsWeight, itsSpeed). - ,
.
C++ ,
. , ,
: Rectangle, rectangle RECTANGLE.
(
class) , cCat cPerson,
.
, Cat Person.
,
. ,
,
(, Chase_Mice)
(, ChaseMice DrawCircle).
.

, ,
.

,
, .
, ,
.

6.

137


,
:
unsigned int GrossWeight; //
Cat Frisky;

// Cat

GrossWeight,
unsigned int, Frisky,
( ) Cat.


,
. ,
,
. Cat,
, Cat.
, Frisky Cat , GrossWeight
unsigned int.
, , .


Cat, Frisky,
.
( .). , 50
- Weight Frisky,
Frisky.Weight = 50;

, Meow() :
Frisky.Meow();

,
. Meow() Frisky.

,
C++
. , :
int = 5;

//

,
5
. :
int.

int ;

// int

= 5;

// 5

138

, 5
:
Cat.itsAge=5;

int.

//

???
Cat , ,
, 5 itsAge (.. ) Cat.
Cat 5
- . :
Cat Frisky;

// int ;

Frisky.itsAge = 5; // = 5;

,
, ,
: , , - , .
: , .
:
Cat Frisky;

// () Frisky

Frisky.Bark();

// Frisky

, ,
. Cat Meow() ().
Cat Meow(),
.

class

.

.(.)
- .


i
I

.

,
.
.
.

-
.


.
public () private (),
.
.
.
.

6.

139

,
.
, , :
class Cat

{
unsigned int itsAge;
unsigned int itsWeight;
void Meow();

>;
itsAge itsWeight, Meow()
, .
, .
Cat, ,
- itsAge main() :
Cat Boots;
Boots.itsAge = 5; // !

, , itsAge, itsWeight
Cat,
- itsAge,
Boots Cat. Boots ,
, ,
.

. -
: Boots Cat,
- ,
?
, Cat
, , .
Boots ,
, . Cat,
,
.
. Cat, :
Meow()

class Cat

<
public:
unsigned int itsAge;
unsigned int itsWeight;
void MeowQ;

};
public (itsAge, itsWeight
.
6.1 Cat .

MeowO)

140

.!.
1: //
2: //

3:
4: include <iostream.h> // cout
5:
6: class Cat //
7: {
8: public: //
9: int itsAge;
10: int itsWeight:

11: };
12:
13:
14: int main()
15: {
16: Cat Frisky;
17: Frisky.itsAge =5; // -
18: cout "Frisky is a cat who is ";
19: cout Frisky.itsAge << " years old.\n";
20: return 0;

21: >

Frisky is a cat who is 5 years old.

6 class.

, .
class.
Cat.
7
11.
8 public, , ,
private ,
.
9 10 - itsAge itsWeight.
14 main() . Frisky
16 Cat, .. Cat. 17
Frisky ( itsAge) 5.
18 19 - itsAge .

8
.
17, ,
.

6.

141


-
.
. - ,
( ).

-.

?
, ?
,
,
.
,
.
,
Cat, itsAge,
, Cat
.
- GetAgeO, Cat
, GetAgeO
. ,
unsigned integer long
.

. , , ,
, ,
.
6.2 Cat, - . ,
, .

.2. _____________________________
1: // Cat
2: // - ,
3: // -
4:
5: class Cat
6: {
7: public:
8: //
9: unsigned int GetAgeO;
10: void SetAge(unsigned int Age);

11:
12: unsigned int GetWeightO;
13: void SetWeight(unsigned int Weight);
14:
15: // -

142

16: void Meow();


17:
18: // -
19: private:
20: unsigned int itsAge;
21: unsigned int itsWeight;

22:
23: };

> . rg . 9 10
- itsAge.
12 13 - itsWeight.
- .
16 - Meow(). Meow()
. -,
, Meow .
- 20 21.
Frisky,
SetAge():
Cat Frisky;
Frisky.SetAge(5); // Frisky

-
,

, ,
,
. . (Stroustrup),
C++, : C++
, (ARM, 1990).

(
private).

- .
-,
- .


- .

6.

143

c l a s s
class :
class _
//

II

class .
- ,
, . , ,
,
':
.
. (), (). .
( ) (.). w

public private.
.

, .
.
1:

unsigned int Age;


unsigned int Weight;
void Meow();

Frisky.Age = 8;
Frisky Weight = 18;
Fiisky.Meowt):

2:

public:

// -

void Start().
void AccelerateO;
void SetYear(int year);

144

// -

private:

' -:-
' int Year;
Char Model [255];

II
Car OldFaithful;

//

int bought;
01dFaithful.SetYear(84);

// 84

// int

bought = OldFaithful.GetYear();

// bought 84

OldFaithful. StartO;

StartO


,
- . ,
, . ,
.
- ,
, . 6.3
Cat,
-.

8.3. Bnpegetem | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: //
2: //

3:
4: ((include <iostream.h>

// cout

5:
6: class Cat

//

7: {
8: public:

// public

9: int GetAgeO;

//

10: void SetAge (int age);

//

11: void Meow();

//

12: private:

// private

13: int itsAge;

// -

14: };
15:
16: // GetAge, ,
17: // - itsAge
18: int Cat::GetAge()
19: {
20: return itsAge;

21: }
22:
23: // SetAge

6.

145

24: // SetAge
25: // - itsAge
26: void Cat::SetAge(int age)
27: {
28:

//

29:

//

itsAge

30: itsAge = ;
31: }
32:
33: // Meow
34: // void
35: //
36: // "Meow"
37: void Cat::Meow()
38: {
39: cout "Meow.\n";
40: }
41:
42: // , ,
43: // , , .
44: int main()
45: {
46: Cat Frisky;
47: Frisky,SetAge(5);
48: Frisky.Meow();
49: cout << "Frisky

is a cat

is ";
years old.\n";

who

50: cout Frisky. QetAge() "


51: Frisky,Meow();
52: return 0;
53: }

Meow.
Frisky is a cat who is 5 years old.
Meow.

614 Cat. 8
public, ,
. 9
GetAgeO, - itsAge,
13. 10 SetAgeO,

itsAge .
11 Meow().
- Meow.
12 ,
- itsAge ( 13).
14.
1821 - GetAge().
. ,

146

,
( 18). - ,
GetAgeO , Cat.
, Get Age () , .
GetAgeO ,
, - itsAge.
, main() ,
Cat. main( )
GetAge(). GetAgeO Cat, - itsAge.
GetAgeO itsAge mal().
26 - Set -
itsAge
( 30). Cat, SetAgeO - itsAge.
37 Meow() Cat.
, Meow,
. , \.
44 main();
. 46 main() Cat
Frisky.
47 - itsAge 5
SetAge(). ,
(Frisky), (.),
(SetAgeO).
.
48 - MeowO, 49
- GetAgeO. 51
Meow() .


. -,
, ( )
, :
int Weight; //
//
Weight =7; //

, :
' j
int Weight = 7; // |

RJTaKi


.
. , ,
, , ,
.

6.

147

- ?
-, .
, void.
, .
, .
,
.
(') .
.
Cat :
CatO:

,
,
.
.


- - ,
,
?
, , ,
, ,
.
.
, .1
. ,
,
, .. .

,
, ?
. ,
,
. ,
,
Cat Rags; // Rags

:
,Cat();

.
Cat , Cat
:
Cat Frisky (5,7);

148

Cat Frisky (3);

, (..
), :
Cat Frisky;

, ,
, .
:
Cat Frisky;

,
, , .
,
, .
, .. .
,
.
,
, .
, ,
. .
6.4 Cat .
Cat
. ,
.

.4. muipgumpH
1: //
2: // Cat
-5
0
4: include <iostream.h>
.

// 01^

6: class Cat

//

7: {
8; public:
9:
10

Cat(int initialAge);
~Cat();

11

int GetAgeO;

12

void SetAge(int age);

13
14
15
16

//
//
//
//
//

void Meow();
private:
int itsAge;

//
// -

};

17
18

// Cat

19

Cat::Cat(int initialAge)

6.

149

20 : <
21: itsAge = initialAge;

22 : }
23:
24: Cat::_Cat()

// ,

25: {
26: }
27:
28: // GetAge, ,
29: // - itsAge
30: int Cat::GetAge()
31: {
32: return itsAge;
33: >
34:
35:

//

36:

//

SetAge,

37:
38: void Cat::SetAge(int age)
39: {
40: // - itsAge
41: // , age
42: itsAge = age;
43: }
44:
45: // Meow
46: // void
47: //
48: // "Meow"
49: void Cat::Meow()
50: {
51: cout << "Meow.\n";
52: }
53:
54: // , ,
55: // , , .
56: int main()
57: {
58: Cat Frisky(5);
59: Frisky.Meow();
60: cout << "Frisky is a cat who is ";
61: cout << Frisky.QetAge() << " years old.\n";
62: Frisky.Meow();
63: Frisky.SetAge(7);
64: cout "Now Frisky is " ;
65: cout << Frisky. |() << " years old.\n";
66: return 0;
67: >

150

Meow.
Frisky is a cat who is 5 years old.
Meow.
Now Frisky is 7 years old.

6.4 6.3 , 9
,
. 10 ,
. , ;
, ,
void.
1922 ,
SetAgeO, .
2426 'Cat -
, ,
.
58 Cat Frisky.
Frisky 5.
- SetAgeO, Frisky
5, - itsAge, 61.
63 itsAge Frisky 7,
SetAgeO. 65.



.
.

-
const
C++ ,
- .
const,
, . , -
SomeFunctionO, void:
void SomeFunctionO const;
i

y/i


Cat :

const.

void SetAge(int anAge);


int GetAge();

6.

151

Set Age () const,


- itsAge. Get ()
const,
. GetAgeO
- itsAge. ,
:
'
void SetAge(int anAge);
int GetAgeO const;

const,
- ,
. , GetAgeO
, , Cat,
, (..
GetAgeO) Cat.

const -,
.
.
const , ,
.
.


, ,
. (
) ,
.
, Cat , -

SetAgeO GetAgeO.
, Cat Meow
- Meow(). ,
- itsAge,
.
GetAgeO SetAgeO,
itsAge, , .
GetAgeO const,
, ,
GetAgeO Cat.
C++ ,
,
.
6.5 , -
.

152

6.5 !

S.S.
// ,
//
include <iostream.h> // cout
class Cat

{
public:
Cat(int initialAge);
"Cat();
int GetAge() const; // const
void SetAge (int age);
void Meow();
private:
int itsAge;

>;
// Cat
Cat::Cat(int initialAge)

{
itsAge = initialAge;
cout << "Cat constructor\n";

}
Cat::"Cat()

//

{
cout "Cat destructor\n";

>
// GetAge const,
// !
int Cat::GetAge() const

{
return (itsAge++); // !

>
// SetAge
//
void Cat::SetAge(int age)

{
// - itsAge
//
itsAge = ;

>

6.

153

44:

45: // Meow
46: // void
47: //
48: // "Meow"
49: void Cat::Meow()
50: {
51: cout << "Meow.\n";
52: }
53:
54: //
55: // ,
56: int main()
57: {
58: Cat Frisky; //
59: Frisky,Meow();
60: Frisky. Bark(); // , .
61: Frisky.itsAge = 7; // itsAge
62: return 0;
63: >

, . I., * .
,
.
11 GetAge( ) -
, const. GetAgeO,
32, - itsAge.
const, itsAge.
, .
13 Meow(),
const. ,
. ,
- Cat, const.
58 Cat Frisky.
Cat ,
. .
58 , .

- ,

^
.
.

60 BarkQ. ,
, .

154

61 7.
-,
.



, .
, , ,
. , , .
, ,
.
, , ,
:
, ,
, .
, .. , ,
, .
. ,
,
.
, ,
. ,
,
,
.



, , .
. ,
.
, .
C++ ,
.. .,
.

, &^
, ,
. ++.
, .
++.

6.

155

,
. ,
, ,
,
, . h, . hp . hpp.
. hpp, .
, Cat CAT, hpp,
..
..
. :
include "Cat.hpp"

CAT. hpp
. include ,

. ,
include .
hpp
,
? ,
.

. ,
, . hpp
, .
,
,
. ,
, .
,
.
, .

. .
. , .. ,
, , .


inline
, . inline
. ,
- GetWeightO :
inline int Cat: .GetWeigtrtt)

{
return itsweight; // - Weight

156

,
:
class Cat

{
public:
int GetWeightO { return itsWeight; } //
void SetWeight(int aWeight);

>;
GetWeightO.
,
.
,
. , ,
:
class Cat

{
public:
int GetWeightO const

{
return itsWeight:
}

//

void SetWeight(int aWeight);

};
6.6 6.7 Cat,
CAT.hpp, .. ,
6.7 Meow() .
> 8 . . c a t c a t , h p p ________________________________
1: iinclude <iostream.h>
2: class Cat
3: {
4:

public:

5:

Cat (int initialAge);

6:

~Cat();

7:

int GetAgeO const { return itsAge; >

8:

void SetAge (int age) { itsAge = age;} // !

// !

9:

void Meow() const { cout << "";} // !

10: private:
11:

int itsAge;

12: };

6.

157

.7. Cat cat .


1: //
2: //

3:
4: include "cat.hpp" // !
5:

6:
7: Cat::Cat(int initialAge) //
8: {
9: itsAge = initialAge;

10: }

11:
12: Cat::Cat() // ,
13: {
14: }
15:
16:
17:
18:
19:
20:
21:

// , ,
// , , " .
int main()
{
Cat Frisky(5);
Frisky. MeowQ;

22: cout << "Frisky is a cat who is ";


23: cout << Frisky.QetAge() << " years old.\n";
24: Frisky.Meow();
25: Frisky.SetAge(7);
26: cout << "Now Frisky is " ;
27: cout << Frisky.GetAge() << " years old.\n";
28: return 0;
29: }

*,. ' - Meow.


Frisky is a cat who is 5 years old.
Meow.
Now Frisky is 7 years old.

-:

, 6.6 6.7,
'
6.4 ,
, CAT. hpp.
7 Get ()
. 8 9 ,
.
4 -6.7' include ' cat.hpp"
CAT. hpp.
cat . hpp , 5.

,
. C++.
hpp,
. include.

158

1829 main( ) 6.4.


,
.

,
-

.
, , , ..,
.
. , .
. .
. . 6.8
Rectangle, RECTANGLE, hpp.
, ,
, Point
, . 6.9 .

6.8. _______________________________
1:

// Rect.hpp

2:

include <iostream.h>

3:

class Point // x,y

4:

5:// ,
6:

public:

7:

void SetX(int ) { itsX = ; }

8:

void SetY(int y) { itsY = y; }

9:

int GetX() const < return itsX;}

10:

int GetY() const { return itsY;}

11:

private:

12:

int itsX;

13:

int itsY;

14:

}; // Point

15:
16:
17:

class Rectangle

18:

19:

public:

20:Rectangle (int top, int left, int bottom, int right);;


21:
22:

'Rectangle () <} . |
ht

23:

int GetTopO const { return itsTop; }

24:

int GetLeftO const { return itsLeft; }

25:

int GetBottomQ const { return itsBottom; }

26:

int GetRightO const { return itsRight; }

'if'.'
7

27:

6.

159

28:

Point GetUpperLeft() const { return itsUpperLeft; >

29:

Point GetLowerLeft() const { return itsLowerLeft: >

30:

Point GetUpperRight() const { return itsllpperRight; }

31:

Point GetLowerRight() const { return itsLowerRight; }

32:
33:

void SetUpperLeft(Point Location) {itsUpperLeft = Location;}

34:

void SetLowerLeft(Point Location) {itsLowerLeft = Location;}

35:

void SetUpperRight(Point Location) {itsUpperRight = Location;}

36:

void SetLowerRight(Point Location) {itsLowerRight = Location;}

37:
38:

void SetTop(int top) { itsTop = top; }

39:

void SetLeft (int left) { itsLeft = left; }

40:

void SetBottom (int bottom) { itsBottom = bottom; }

41:

void SetRight (int right) { itsRight = right; }

42;
43:

int GetArea() const;

44:
45: private:
46:

Point itsUpperLeft;

47:

Point itsUpperRight;

48:

Point itsLowerLeft;

49:

Point itsLowerRight;

50:

int itsTop;

51:

int itsLeft;

52:

int itsBottom;

53:

int itsRight;

54: };
55: // Rect.hpp

6.9. rect. ____________________________


1:
2:

// rect.
include "rect.hpp"

3:

Rectangle::Rectangle(int top, int left, int bottom, int right)

4:
5:
6:
7:

{
itsTop = top;
itsLeft = left;
itsBottom = bottom;

8:

itsRight = right;

9:
10: itsUpperLeft.SetX(left);
11: itsUpperLeft.SetY(top);
12:
13:
14:
15:
16:
17:

itsUpperRight.SetXtright);
itsUpperRight.SetY(top);
itsLowerLeft.SetX(left);
itsLowerLeft.SetY(bottom);

18:

760

19: itsLowe rRight.SetX(right);


20: itsLowerRight.SetY(bottom);

21: }
22:
23:
24:
25:
26:
27:

// , ,
// ,
int Rectangle::GetArea() const
{

28: int Width = itsRignt - its Left ;


29: int Height = itsTop - itsBottom;
30: return (Width * Height);
31: }
32:
33: int main()
34: {
35: // Rectangle
36: Rectangle MyRectangle (100, 20, 50, 80 );
37:
38: int Area = MyRectangle.GetArea();
39:
40: cout << "Area: "<< Area << "\n";
41: cout "Upper Left X Coordinate:";
42: cout MyRectangle. GetllpperLeft( ), GetX( ) ;
43: return 0;
44: }

Area: 3000
Upper Left X Coordinate: 20

3-14 6.8 Point,


, .
Point .
.
Point ( 12 13) (itsX itsY). .
.
.
( ). ,
.
Point nline- ,
X Y,
7-10. Point
, . ,
.
17 Rectangle,
, .
Rectangle ,
top (), left (), bottom () right (). -

6.

161

, , - (. 6.9), (
Point).
- , Rectangle
GetAreaO, 43.
28 29
6.9.
, .

UpperLeft X. GetUpperLeftO
Rectangle,
, itsUpperLeft.
itsUpperLeft Point, itsX
, GetUpperLeftO .
itsX
GetX().
33 6.9 .
36 , , . ,
, ,
( , ).
36 ( Rectangle)
, Left, Bottom Right.
37 int.
.
, - GetAreaO Rectangle.
Rectangle Rectangle ,
GetAreaO.
6.8 Rect.hpp.
, Rectangle,
, GetAreaO int.
Rectangle GetAreaO.
, Rectangle
GetAreaO, , Rectangle.


?
, ,
.

class
. C++
, .
, , -
struct,

162

. ,
,
.
6.8 :

3 class Point struct

17 class

Rectangle

Point;

struct

Rectangle.

.
.



, , ,
. . C++
. ,
. C++, , ,
struct class,
.


. ,
. -.

const
, .
,
,
.

, .
, , .
-,
, . , , . -
- .
,
. ,
- .
,
, , . hpp.
.
.
, ,
, .

6.

163


?
. , .
,
.
,
, , .
Cat itsAge,
Cat Friscky Boots, Boots
- itsAge Friscky?
. - ,
. ,
Friscky Boots Cat, - Friscky
( Friscky),
Boots.
- ?
-
, , . ,
Cat GetAgeO, Cat
( Cat), , -
- .
const ,
const
?
- ,
const
, , GetAge()
Cat, :
if (itsAge = 100) cou << "Qio! \";

GoiAyeO const
.
itsAge 100,
100 itsAyn. , (
cunsi) , ,
.
, ,
. , . ,
, (
), .
C++?
struct ,
.
, .
.

164

, , .
,
, .


,
.
, .
,
.


1. ?
2. ?
3. ?
4.


?
5. - ?

(public)

(private)

6. - ?
7.


- itsAge?

8.

?
?

Cat,

9.

- Meow Cat,
void?
10. ?

1.

,
-: (), yearsOfService
().

Employee

()
) Salary

2.

Employee, -
-.
3. Employee,
Employee; - age, YearsOfService Salary,
.
4.

3 Employee,
, , 1
.

5. Employee , -
age, YearsOfService Salary .

6.

165

6. : ?
class Square

{
public:
int Side;

}
7. : ?
class Cat

<
int GetAgeO const;
private:
int itsAge;

};
8. : ?
class TV

{
public:
void SetStation(int Station);
int GetStation() const;
private:
int itsStation;

};
main()

<
TV myTV;
myTV.itsStation = 9;
TV.SetStation(IO);
TV my0therTv(2);

166



.
if. :

if/else



. (. 5)
.
.

goto
, ,
.
.
, .
C++ , (:).
,
. goto,
. goto 7.1.

7.1. g o t o _________________________________
1:

// 7.1.

2:

// goto

3:
4:

include <iostream.h>

7.

167

5:
6:

int

main()

7: {

8
9:

int counter = 0; //
loop: counter ++;

//

10

cout. << "counter: " << counter << "\ n";

11

if (counter < 5) //

12

goto loop; //

13
14

cout

15

return 0;

<<

"Complete.

Counter:

"

<<

counter

<<

",\

n";

16

counter:

counter:

counter:

counter:

counter: 5
Complete. Counter: 5.

8 counter .
loop: 9 .
counter . 11
counter. ,
goto,
9. ,
counter .
.

yoo
goto , ,
. goto
.

, .

: goto.
goto
, : for, while do. . .while.
goto
,
.

goto .
ANSI . ,
: !
!

168

while
, while,
,
. 7.1 counter
, . 7.2
, whi 1 .

7.2. w h i l e __________________
1: // 7.2.
2: // while

3:
4: include <iostream.h>

5:
6: int main()

7: {
8:

int counter = 0;

//

9:
10:

while(counter < 5) //

11 : {
12:

counter++;

13:

cout << " counter: " << counter << "\ n";

14:

//

15:
16: cout << " Complete. Counter: " << counter << ",\ n";
17: return 0:
18: }

counter:

counter:

counter:

counter:

counter: 5
Complete. Counter: 5.


while.
, , ,
.
counter, ( 10). ,
. 12
, 13 .
, ( 11 14)
15.

7.

169

while
, while,

. while
C++.
: && ( ), 11 ( ), ! ( ).
7.3
while.

7.3. w h i l e ______________________________________
1: // 7.3.
2: // while

3:
4: include <iostream.h>
5:
6: int main()
7: {
8:

unsigned short small;

9:

unsigned long large;

10:

const unsigned short MAXSMALL=65535;

11:
12:

cout << "Enter a small number: ";

13:

cin >> small;

14:

cout << "Enter a large number: ";

15: cin >> large;


16:
17:

cout "small: " << small <<

18:
19:

//

20: while (small < large && large > 0 && small < MAXSMALL)

22: {
23:
24:

if (small % 5000 == 0) // 5000


cout

25:
26:

small++;

27:
28:

large-=2;

29: }
30:
31: cout << "\ nSmall: " small " Large: " large << endl;
32: return 0;
33: }

Enter a small number: 2


Enter a large number: 100000
small: 2..........
Small: 33335 Large: 33334

170

.
small large.
, ,
. : , .
1215 . 20
.
1. small large.
2. large .
3. small MAXSMALL.
, 23, small 5000,
small . small 5000 ,
0.
. 26
small 1, 28 large 2.
, .
29, .

break u continue

. continue.
, ,
. break.
7.4.
. ,
, .
, small
. large ,
(skip). , small
, large. large
(target), .
, , target.

7.4. b r e a k c o n t i n u e
1 :

// 7.4.

2:

// break continue

3:
4:

include <iostream.h>

5:
6:

int main()

7:

8:

unsigned short small;

9:

unsigned long large;

10;

unsigned long skip;

11;

unsigned long target;

12:

const unsigned short MAXSMALL=65535;

13:

7.

171

14:

cout "Enter a small number:

15:

cln small;

16:

cout "Enter a large number: ";

17:

oin large;

18:

cout << "Enter a skip number: ";

19:

cin skip;

20:

cout "Enter a target number: ";

21:

cln >> target;

22:
23:

cout "\ n"

24:
25:

//

26:

while (small < large && large > 0 && small < MAXSMALL)

27;
28: {
29:
30:

small++;

31:
32;

if (small % skip == 0) // large?

33;

34;

cout << "skipping on:" << small << endl;

35:

continue;

36:

37;
38:

if (large == target) //

39:

40:

cout << " Target reached!";

41:

break;

42:

43:
44:

large-=2;

45:

} //

46:
47;

cout << "\ nSmall: " << small << " Large: " << large << endl;

48: return 0;
49: }

Enter a small number: 2


Enter a large number: 20
Enter a skip number: 4
Enter a target number: 6
skipping on 4
skipping on 8
Small: 10 Large: 8

172


, , *
, .
.
small large, large small
SMALLINT, .
32 small
skip. small skip, continue
( 26).
large.
target large 38. ,
.
, break 46.

while(true]
, ,
,
C++. , .

true. 7.5 ,
.

7.5. w h i l e ______________________________
1: // 7.5.
2: // ""

3:
4: include <iostream.h>
5:
6: int main()
7: {
8:

int counter = 0;

9:
10:

while (true)

11: {
12:

counter ++;

13:

if (counter > 10)

14:

break;

15:

16:

cout << "Counter: " << counter << "\ n";

17:

return 0;

18: }

".
4-'
counter

7.

Counter: 11

, , 10,
. ( 12)
. ,

173

counter 10.
14, counter ( 16).
,
. while.
counter .
C++
. ,
.
break

du...while
while ,
.
, ,
,
. 7.6.

7.. w h i l e ________________________________
1:

// 7.6.

2:// ,
3:

// .

4:
5:

include ciostream.h>

6:
7:

int main()

8:
9:

{
int counter;

10;

cout "How many hellos?: ";

11:

cin counter;

12:

while (counter > 0)

13:

14:

cout << "Hello!\ n";

15:

counter--;

16:

17:

cout << "Counter is OutPut: " << counter;

18:

return 0;

19:

pjffl How many hellos?: 2


Udmm Hello!
Hello!
Counter is OutPut: 0
How many hellos?: 0
Counter is OutPut: 0

174

10 ,
counter. 12
, .
,
. 0. ,
.
.
, ?
while ,
.
if counter.
If (counter < 1) //
counter = 1;

, .

du...wlrilc
do...while
.
. 7.7 ,
while do.. while.

7.7. d o . . w h i l e _____________________________________
1:

// 7.7.

2:

// do...while

3:
4:

include <iostream.h>

5:
6:

int main()

7:
8:

{
int counter;

9;

cout << "How many hellos? ";

10:

cin >> counter;

11:

do

12 : {
13:

cout << "Hello\ n";

14:

counter--;

15:

} while (counter >0 );

16:

cout "Counter is: " << counter << endl;

17:
18:

return 0;
}

How many hellos? 2


Hello
Hello
Counter is: 0

7.

175

f'

9
, counter. do.. while
,
. 13 ,
14 counter .
15. ,
( 13).
16.
do.. while break continue
, while.
.
, .

for
while
: ,

( 7.8).
7 . 8 . while___________________________
1: // 7.8.
2: // while
3:
4: include <iostream.h>
5:
6: int main()
7: {
8:

int counter = 0;

9:
10:

while(counter < 5)

11 : {
12:

counter++;

13:

cout << " Looping!

14:

15:
16: cout << "\ nCounter: " << counter << " \ n";
17: return 0;
18: }

Looping! Looping! Looping! Looping! Looping!


Counter: 5.

8 counter
. 10 ,
12 . 13

176

, . ,
.
for , ,
. : ,
. for
, ,
.
.
for .
, , ,
for, C++
, - . for
, .
, while.
(
).
C++. , , for
C++,
, .
for 7.9.
7 . 8 . f o r ___________________________________________
1:

// 7 ,9 .

2:

// for

3:
4:

((include <iostream. h>

5:

6 :

i n t

7:

<

8:

int counter;

9:

for (counter = 0; counter < 5; counter++)

10:

m a i n ( )

cout << " Looping! ";

11:
12:

cout << "\ nCounter: " << counter << .\ n";

13:

return 0;

14:

Looping! Looping! Looping! Looping! Looping!


' ' Counter: 5,

9 for ,
counter.
counter
. , 10.
.
l

7.

177

for
f o r

. , f o r

(, ),
.

f o r
for :
f or (, ,

||

',^ ;

. C++,
.
true, ,
, , ,
.
1:
/ ;;1'::;^|;':^

for(int i;=0;
cout "Hello! "

2:
f o r ( i n t

0 ;

cout << "He] lo! " e

t;>; <:out <<:^h"valui0fi%sr^". ^ i

} :-r:: .
f

1. .
2. , .
3. true, ,
.
2 3 .


for ,
.
,
. 7.10
, .

178

7.10. f o r
1

// 7.10.

//

// for

4
5

ftinclude <iostream.h>

6
7

int main()

for (int i=0, j=0; i<3

10: cout << ": "

i++, j++)
<< " j: " << j << endl;

11: return 0;
12: }

i: 0 j:
........ i: 1 j: 1
i: 2 j: 2

9 i j .
i<3 , ,
.
. for,
- .
10 .
, . ,
.
.

for
for .
. , ,
for (;).
for, 7.11,
while.
7 . . f o r ______________________________________________
1 : // 7 .1 1 .

2: // for

3:
4: #include <iostream.h>
5:
6: int main()
7: {
8:

int counter = 0;

9:
10:

for( ; counter < 5; )

7.

179

11 : {
12:

counter++;

13:
14:

cout "Looping!
}

15:
16:

cout << "\ nCounter: " << counter << ",\ n";

17:

return 0:

18: }

Looping! Looping! Looping! Looping! Looping!


Counter: 5.

,
while 7.8. 8
counter. for,
10, .
for . ,

while (counter < 5).

, C++
. 7.11
C++,
for .
for,
break continue. for
7.12.
7 . 1 2 . f o r _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: // 7.12.
2: // for

3:
4: include <iostream.h>
5:
6: int main()
7: {
8:

int counter=0;

9:

int max;

10:

cout << " How many hellos?";

11:

cin >> max;

12:

for (;;)

13:

//

14:

if (counter < max)

15:

16:

cout "Hello!\ n";

17:

counter++;

180

,//

//

//

18: }
19:

else

20:

break;

21: }
22: return 0;
23: }

* i How many hellos?3

1*

11
1iI
Hello!
Hello!
Hello!

for
. , .
8 .
( 14), ,
, , 17
. , break 20
.
,
, for( ;; ) while( true )
.
switch.

for
for
,
. , ,
(;).
for. 7.13.
7 . 1 3 . f o r _ _ _ _ _ _ _ _ _ _ _ _
1:

// 7.13.

2:

// for

3:

// ""

4:
5:

include <iostream.h>

6:

int main()

7:

8:

for (int i = 0; i<5; cout "i: " i++ endl)

9:

10:

return 0;

11 :

: 2
:
: 4

7.

181

for 8 .
i
0. i<5, , ,
for
.
for,
. ,

. :
8: for (int i = 0; i<5; i++)
9:

cout << "i: " << i << endl;

,
.


, , .
.
7.14 .
7 . 1 4 .
1: // 7.14.
2: // for

3:
4: include <iostream.h>
5:
6: int main()
7: {
8:

int rows, columns;

9:

char theChar;

10:

cout << "How many rows? ";

11:

cin rows;

12:

cout << "How many columns? ";

13:

cin >> columns;

14:

cout << "What character? ";

15:

cin >> theChar;

16:

for (int i = 0; i<rows; i++)

17:

18:
19:
20:

for (int j = 0; j<columns; j++)


cout << theChar;
cout "\ n";

21: }
22: return 0;
23: }

182

How many rows? 4


How many columns? 12
What character? x
xxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxxx


, ,
. 16 i,
.
( 18)
. j 0
. 19 , ,
. .
,
(j<columns). j
columns, .
(12 )
20 .
(i<rows) , ,
.
:
. j ,
.
,
. ,
:
, columns,
rows.

- for
, for,
. ,
ANSI, , ,
. , ,
, .
,
.
include <iostream.h>
int main()

{
//

for (int i = 0; i<5; i++)

{
cout << "i: " << i << endl;

7.

183

= 7; // i

return 0;

}
, ,
ANSI.
, ,
i = 7.
.
include <iostream.h>
int main()

{
int i; //
for (int i = 0; i<5; i++)

{
cout << "i: << i << endl;

>
i

7;

//

return 0;

>


5
. , 1, 1,
2, 3, .
1,1,2,3,5,8,13,21,34...

, - (n-I)-ro
. ( 7.15).

(-2)-

7.15. - ________________
1;

// 7.15.

2:

// n-

3:

//

4:
5:

include <iostream.h>

6:

8:
9:
10:

int fib(int position);


int main()

11:

12:

int answer, position;

13:

cout << "Which position? ";

14:

cin >> position;

15:

cout <x "\ n";

16:
17:

184

answer = fib(position);

18:

cout << answer << " is the

19:

cout << position << "Fibonacci number.\ n";

20:

return 0;

21: }
22:
23: int fib(int n)
24: {
25:

int minusTwo=1, minus0ne=1, answer=2;

26:
27:

if (n < 3)

28:

return 1;

29:
30:

for (n -= 3; n; n--)

31:

<

32:

minusTwo = minusOne;

33:

minusOne = answer;

34:

answer = minusOne + minusTwo;

35:

36:
37:

return answer;

38: }

Which position? 4
3 is the 4th Fibonacci number,
Which position? 5
5 is the 5th Fibonacci number.
Which position? 20
6765 is the 20th Fibonacci number.
Which position? 100
3314859971 is the 100th
Fibonacci number.
l-'"

* . , 7.15,
. ...
.
, for. ,
.
13
. fib(),
.
, 1. ,
2, .
1.

: minusTwo=1, minus0ne=1, answer=2.


, , 3,
.

2.


. :
minusTwo minusOne;

minusOne answer;

1.

185

minusOne minusTwo answer;

3. , answer.
,
. , ,

1, 1, 2,

. (2+1=3),

2 3, 5. ,
.
for,
. C++. -
' =0. C++ 0
false,
. ,
for (-=3; !=0; --)

. ,
C++
, .
. ,
25- (. 5)
. , ,
, ,
.
. ,

.
,
.
.

switch
4 if if/else.
if
, ,
. C++
switch. if ,
,
. switch :
switch ()

{
case : ;
break;

186

case : ;
break;

case _: ',
break;
;

default:

}
switch ,
.
,
, ( ,
). ._____________________

s w i t c h
. :
switch: {)

:;lgi

: ;
case : ;
case _: ;
defauIt:: ;

v)

' '. :

switch
,

.
,

casf,

sw. :; h, ,

'..V-'.:
: -jk.

:.*

.!!; ,
,

vw: ,
.
1:
switch (choice)

{ 1.. ...
case 0:
cout << "Zero!" endl;
^Abreak;
case 1
'
':~;i
cout "One!" endl;
;::.::;- break;
case 2:
' :: cout "Two!" endl;
/ : break;

<< "Default!" endl;

7.

187

2:

.:!

switch'^

case 0: ' vcase 1:


case 2 :

i!':'::';.:;'
; : v r s >
i;,/':\ ; K ' ^ ' v '
: ';:1-: f
;:"'cout "Less than 3!" endi;

< j

case 3:
.. .........*?c6ifc?<? "Equa Is. .31' .:'<<."*endl:i;'.v

default:
cout "Greater than 3!" endl;

$.....
break , case,
case.
, break . , break
, .
switch 7.16.
7 . 1 . s w i t c h __________________________________________
1: / / 7.16.
2: // switch

3:
4: include <iostream.h>
5:
6: ' int main()
7: {
8:

unsigned short int number;

9:

cout << "Enter a number between 1 and 5: ";

10:

cin >> number;

11:

switch (number)

12: {
13:

case 0: cout << "Too small, sorry!";

14:

break;

15:

case 5: cout << "Good job!\ n"; // fall through

16:

case 4: cout << "Nice Pick!\ n"; // fall through

17:

case 3: cout << "Excellent!\ n"; // fall through

18:

case 2: cout << "Masterful!\ n"; // fall through

19:

case 1: cout << "Incredible!\ n";

20:

break;

21:

default: cout << "Too large!\ n";

22:
23:

break;
>

24: cout "\ n\ n";


25: return 0;
26: }

188

Enter a number between 1 and 5: 3


Excellent!
Masterful!
Incredible!
Enter a number between 1 and 5: 8
Too large!

.
switch. 0, case 13 Too small, sorry!,
break switch.
5, 15 .
16, ,
20. break switch.
, 1 5
. , 5, 21
default, Too large!.

switch
for(;;).
, ,
break, .
( 7.17).
,
. , .
,
. break,
7 . 1 7 . _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1:
2:

/ / 7,17.
//

3:
4:
5:

//
include <lostream.h>

6:

//

7:
8:
9:

Int menu();
void DoTaskOnoO;
void DoTaskMany(int);

10
11
12

int main()

13
14
15
16
17
18
19

bool exit = false;


for (;;)
int choice = menu();
switch(choice)

20

21

7,

case (1)
DoTaskOneO;

189

22:

break;

23 :
24:

case (2):
DoTaskMany(2);

25:

break;

26:
27:
28:

case (3):
DoTaskMany(3);
break;

29:
30:
31:

case (4):
continue;
break;

32:
33:

case (5):
exit=true;

34:

break;

35:
36:
37:
38:

//

default:
cout << " Please select again!\ n";
break;
>

// switch

39:
40:
if (exit)
41:
break;
42: }
//
43: return 0;
44: }// main()
45:
46: int menuQ
47: {
48:
int choice;
49:
50:

cout " **** Menu ***\ n\ n;

51:

cout << "(1) Choice one.\ n";

52:
53:
54:
55:
56:

cout << "(2)


cout << "(3)
cout << "(4)
cout << "(5)
cout << ":

57:
58:

Choice two.\ n";


Choice three.\ n";
Redisplay menu.\ n";
Quit.\ n\ n";
";

cin >> choice;


return choice;

59: }
60:
61: void DoTaskOneO
62: {
63:
cout "Task 0ne!\ n";
64: }
65:
66: void DoTaskMany(int which)
67: {
68:
69:

if (which == 2)
cout << "Task Two!\ n";

70:

else

71:
72: }

190

cout << "Task Three!\ n";

: **** Menu ****


:*****, (1) Choice one.
(2) Choice two.
(3) Choice three.
(4) Redisplay menu.

(5) Quit.

:1
Task One!
**** Menu ****
(1) Choice one.
(2) Choice two.
(3) Choice three.
(4) Redisplay menu.

(5) Quit.
: 3

Task Three!
**** Menu ****
(1) Choice one.
(2) Choice two.
(3) Choice three.
(4) Redisplay menu.

(5) Quit.
: 5

,
.
switch.
15. menu()
.
switch 1838.
case
(1): ( 21). , 21, DoTaskOneO,
.
break (
22). break switch
39. , 40, exit. ,
break 41.
( 15).
continue 30.
, ,
, .
, break, if ,
exit false, .
continue
exit.

7.

191


C++
. while , ,
. do. . . while
. for ,
. , ,
, for.
.
goto ,
, .
continue
while, do.. .while for, a break .


, ,
?

if/else

switch,


switch.
while do..

if,

while?

,
do,..while. while.
while for?

,
,
for. while.
, ?

, ,
, ,
.
, f

(;;)

while(true) ?


,
.
, .
,
.

192


1. for -?

2. goto?
3. for ,
?
4. while for?
5. , ? .
6. ?

1. for

(int

= 0; <

100; ++)?

2. for, 10x10.
3. for, 100 200 2.
4. while, 100 200 2.
5. do..

while,

100 200 2.

6. : .
int counter = 0;
while (counter < 10)

{
cout << "counter: " counter;

>
7. : .
for (int counter = 0; counter < 10; counter++);
cout << counter << " ";

8. : .
int counter = 100;
while (counter < 10)

{
cout << "counter: " << counter;
counter--;

}
9. : .
cout << "Enter a number between 0 and 5: ";
ein >> theNumber;
switch (theNumber)

7.

193

case 0:
doZero();
case
case 2
case 3
case 4

//
//
//
//

case 5
doOneToFive();
break;
default:
doDefault();
break;

194



#include <iostream.h>
intintboolfalsetrue
enum CHOICE { DrawRect = 1, GetArea,
GetPerim, ChangeDimensions, Quit} ;
// Rectangle
class Rectangle

{
public:
// constructors
Rectangle(int width, int height);
Rectangle();
//
int GetHeightO const { return itsHeight; }
int GetWidth() const { return itsWidth; }
int GetArea() const { return itsHeight * itsWidth; }
int GetPerim() const { return 2*itsHeight + 2*itsWidth; }
void SetSize(int newWidth, int newHeight);
//

private:
int itsWidth;
int itsHeight;

//
void Rectangle::SetSize(int newWidth, int newHeight)

{
itsWidth = newWidth;
itsHeight = newHeight;

1.

195

34:

35:
36:Rectangle:: Rectangle(1nt width, int height)
37:

38:

itsWidth = width;

39:
40:
41 :

itsHeight = height;
>

42:

Rectangle:;"Rectangle() { }

43:
44:

int DoMenuO;

45:

void DoDrawRect(Rectangle);

46:

void DoGetArea(Rectangle);

47:

void DoGetPerim(Rectangle);

48:
49:

int main ()

50:
{
51:// rectangle 30,5
52:

Rectangle theRect(30,5);

53:
54:

int choice = DrawRect;

55:

int fQuit = false;

56:
57:

while (!fQuit)

58:

59:

choice = DoMenuO;

60; if (choice < DrawRect || choice > Quit)


61:

62:cout << "\ nlnvalid Choice, please try again.\ n\ n"


63;

continue;

64:

65:

switch (choice)

66;

67:

case DrawRect:

68:
69:

DoDrawRect(theRect) ;
break;

70:
71:

case GetArea:
DoGetArea(theRect) ;

72:

break;

73:

case GetPerim:

74:

DoGetPerim(theRect);

75:

break;

76:

case ChangeDimensions:

77:

int newlength, newWidth;

78:
79:

cout "\ nNew width: ";


cin >> newWidth;

80 :
81 :

cout << "New height : " ;


cin >> newLength;

82: theRect.SetSize(newWidth, newLength);


83:

196

DoDrawRect(theRect);

84:

break;

85:

case Quit:

86:

fQuit = true;

87:

cout "\ nExiting...\ n\ n"

88:

break;

89:

default:

90:

cout "Error in choice!\ n"

91:
92:

fQuit = true;
break;

93:

> // end switch

94: } // end while


95: return 0;
96; }

// end main

97:
98: int DoMenu()
99: {
100

int choice;

101

cout << "\ n\ n *** Menu *** \ n";

102

cout

103
104

cout << "(2) Area\ n";


cout
cout

105
106

"(1)

Draw

Rectangle\

n;

"(3) Perimeter\ n";


"(4) Resize\ n";

cout "(5) Quit\ n";

107
108

cin >> choice;

109

return choice;

110 }
111
112

void DoDrawRect(Rectangle theRect)

113

114

int height = theRect.GetHeightO;


int width = theRect.GetWidth();

115
116
117

for (int i = 0; i<height; i++)

118
119

<
for (int j = 0; j< width; j++)

120

cout <<

121
122
123
124

cout << "\ n";

}
}

125
126

void DoGetArea(Rectangle theRect)

127

128
129
130

131

void DoGetPerim(Rectangle theRect)

cout << "Area: " << theRect.GetArea() endl;

132

1.

133:

cout

<<

"Perimeter:

"

theRect.GetPerim()

endl;

134: }
<0utput>
* * * Menu * * *
(1) Draw Rectangle
(2) Area
(3) Perimeter
(4) Resize
(5) Quit

******************************
******************************
******************************
******************************
******************************

*** Menu ***


(1) Draw Rectangle
(2) Area
(3) Perimeter
(4) Resize
(5) Quit
2
Area: 150
*** Menu ***
(1) Draw Rectangle
(2) Area
(3) Perimeter
(4) Resize
(5) Quit
3
Perimeter: 70
*** Menu ***
(1) Draw Rectangle
(2) Area
(3) Perimeter
(4) Resize
(5) Quit
4
New Width: 10
New height: 8

198

* * * Menu * * *
(1) Draw Rectangle
(2) Area
(3) Perimeter
(4) Resize
(5) Quit
2

Area: 80

** * Menu * * *
(1) Draw Rectangle
(2) Area
(3) Perimeter
(4) Resize
(5) Quit
3
Perimeter: 36
* * * Menu * * *
(1) Draw Rectangle
(2) Area
(3) Perimeter
(4) Resize
(5) Quit
5
Exiting. . .


, .
, ,
, , . ,
, .

, .
626 Rectangle.
,
. 2940
- , inline.
, ,
4447, 49.
,
: , ,
, .
55,
, . ,

.

1.

199

, ChangeDimensions,
, switch.
ChangeDimensions ,
.
,
DoChangeDimensions(), Rectangle
,
, main() .
8, , 10,
, , ,
.
main().
,
switch . ,
,
1 5, ,
, .
60 , ,
, . ,
. ,
switch default,
.
, .


!
C++! ,
. , ,
.
, -
,
C++.
,
, , .

200



++.
. ,
, -
.


.
++.
,
, , ,
. 9 ,
. 10
, 11
- .
12
. 13 -
, 14
.



++. :


,
. ,
.
, , .
, .


, .
, , ,
.
.
, . . 8.1

1:.
,
.
-
.
(&). 8.1.

202

theAge

I......................................

1I!I!

10110101 11110110
01110110 11101110

____I___ I___ I___ I___ I___ I___ I___ I___ I___ I___ I___ I I
100 101 102 103 104 105 106 107 108 109 110 111 112 113
- 1
unsigned long int theAge = 4 = 32
theAge
theAge = 10

. 8.1. theAge

8.1. ________________________________________
1:

// 8.1.

2:

//

3:
4:

#include <iostream.h>

5:
6:

int main()

7:

8:

unsigned short shortVar=5;

9:

unsigned long longVar=65535;

10:

long sVar = -65535;

11:
12:

cout << "shortVar:\ t" << shortVar;

13:

cout " Address of shortVar:\ t";

14:

cout &shortVar "\ n";

15:
16:

cout "longVar:\ t" longVar;

17:

cout " Address of longVar:\ t" ;

18:

cout &longVar << "\ n";

19:

20:

cout "s.Var:\ t" sVar;

21:

cout << " Address of sVar:\ t" ;

22:

cout << &sVar << "\ n";

23:
24:

return 0;

25:}

shortVar: 5

Address of shortVar: 0x8fc9:fff4

longVar: 65535 Address of longVar: 0x8fc9:fff2


sVar: -65535 Address of sVar: 0x8fc9:ffee

( .)

8.

203

\ :
v 8 unsigned short, 9 unsigned
long, 10 long. 12-16
, (&).
80386
shortVar 5, 0x8fc9:fff4.
.
.
.
short 2 ,
4 long.
. 8.2.

. ,
.
, ,
.
long . ,
.


,
.
.
, howOld int.
, :
int *pAge = 0;

int. ,
int.
, .
(, int) ,
.
- , , .
, .
.
, 0, .
- .
, ,
0.
.
0,
- , howOld. ,
:
unsigned short int howOld = 50; //
unsigned short int *pAge = 0; .

//

pAge = &how01d;

//

howOld

204

. 8.2.

howOld unsigned short int


50. unsigned short
int, 0. (*),
, , .
howOld.
(&) howOld.
, , ,
.
howOld,
50.
:
unsigned short int howOld = 50;

//

unsigned short int * pAge = &how01d;

// howOld

howOld.
, .
50. howOld
,
howOld, .
, .
,
, .


,
.
(
. pointer), pNumber.


( )
, , .
,
. ,
unsigned short int, ,
:
unsigned short int yourAge;
yourAge = howOld;

,
. yourAge howOld,
, , :
unsigned short int yourAge;
yourAge = *pAge;

(*)
, . ,
: , , ,
yourAge.

206


: .
, , , :
unsigned short * pAge = 0; //
// unsigned short

,
,
, , :
* = 5; // 5 pAge

(*).
.

,
C++,
, , ,
, , , .
.
:
int theVariable = 5;
int * pPointer = &theVariable ;

theVariable.
5. int,
theVariable. pPointer
theVariable. , ,
pPointer, 5. . 8.3 .
theVariable

pPointer

IIII
0000 0000
0000 0101
V. J
5

IIII

" ".........." I I I
0000 0000 0000 0110
0000 0000 0000 0101
V. _ 1
' ' Y...... '
101
IIIII

100 101 102 103 104 105 106 107 108 109

. 8.3.

8.

207


- ,
. 8.2
.
8.2. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1:

// 8.2.

2:

3:

include <iostream.h>

4:
5:

typedef unsigned short int USHORT;

6:

int main()

7:

8:

USHORT myAge; //

9:

USHORT * pAge = 0; //

10:

myAge = 5;

11:

cout << "myAge: " << myAge << "\ n";

12:

pAge = &myAge; // pAge myAge

13:

cout << "*pAge: " << *pAge << "\ n\ n";

14:

cout << "*pAge = 7\ n";

15:

*pAge = 7; // myAge 7

16:

cout << "*pAge: " *pAge << "\ n";

17:

cout << "myAge: " myAge << "\ n\ n";

18:

cout << "myAge = 9\ n";

19:

myAge = 9;

20:

cout << "myAge: " << myAge << "\ n";

21:

cout << "*pAge: " << *pAge << "\ n";

22:

23:

return 0;

24:

>

myAge:

*pAge: 5
pAge = 7
*pAge: 7
myAge:

myAge = 9
myAge:

*pAge: 9

: myAge unsigned short pAge,


. 10 pAge
5, 11 .
12 pAge myAge.
, , pAge,
( 13). ,
ill

208

. 15 , ,
7.
7. ( 16, 17).
19 .
9. 20 21
( ) .

,

, . ,

. ?
, 8.3.
8.3. ?_______________________________
1:

// 8.3. ?

2:

3:
4:

#include ciostream.h>

5:
6:

int main()

7:

8:

unsigned short int myAge = 5, yourAge = 10;

9:

unsigned short int * pAge = &myAge; //

10:

cout << "myAge:\ t" << myAge << "\ t yourAge:\ t" << yourAge "\ n";

11:

cout << "&myAge:\ t" << &myAge << "\ t&yourAge:\ t" &yourAge << "\ n";

12:

cout << "pAge:\ t" << pAge << "\ n";

13:

cout << "*pAge:\ t" << *pAge << "\ n";

14:

pAge = &yourAge; //

15:

cout << "myAge:\ t" << myAge << "\ t yourAge:\ t" << yourAge "\ n";

16:
17:

cout << "&myAge:\ t" &myAge << "\ t&yourAge:\ t" << SyourAge << "\ n";
cout << "pAge:\ t" << pAge << "\ n";

18:

cout << "*pAge:\ t" << *pAge << "\ n";

19:
20:

cout << "&pAge:\ t" << &pAge << "\ n";


return 0;

21:

>
myAge:
&myAge:
pAge:

5
0x355C

10

&yourAge:

0x355E

0x355C

* pAge:

myAge:

&myAge:

yourAge:

0x355C

pAge:

0x355E

pAge:

10

&pAge:

0x355A

yourAge:

10

&yourAge:

0x355E

( .)

8.

209

8 unsigned short myAge


, 9, ().
myAge.
10 11 myAge .
myAge
13. ,
, .
.
14 yourAge.
.
, ,
you , .
19 .
, ,
. .
yourAge.

(*)

,
,

,
.

,
.


, ,
, (*),
, :
unsigned short int * pPointer =0;

(&), :
unsigned short int theVariable = 5;

unsigned short int * pPointer = & theVariable;

(*):
unsigned short int theValue = pPointer

210



.
. , ,
?
. ,
, ++ ,
.
:

;
;
.

, 5

, ;
();
;
.

.
,
.
, .

, .
, ,
, , , ,
.

,
.
.
, ,
, ,
. ,
. ,
.

8.

211

, . ,
. ,
, , , .
, .
,
. .
, , ,
. ,
. ( )
( ). , ,
, .
, .

. ,
,
.
,
, .
, ,
.

,
, , .

, .

. , , .

new

new. new ,
. ,
. , , new unsigned short int,
, new long .
new
. . ,
unsigned short
:
unsigned short int * pPointer;
pPointer = new unsigned short int;

, :
unsigned short int * pPointer = new unsigned short int;

pPointer
, unsigned short. pPointer
.
- , :
pPointer = 72;

212

: 72 ,
pPointe.
,
new .
, 20.

delete
, , ,
. delete,
. delete , .
, , ,
, . ,
, . ,
new, ,
. .
.
, ,
.
, delete, :
delete pPointer;

,
, .
.
8.4 , ,
, .
'

delete
,
,

. delete


. delete
, :

Animal *pDog = new Animal;


delete pDog; //
pDog = 0 //
// ...
delete pDog; // ,

8 . 4 . ,
1;

// 8,4,

2;

// ,

3;
4:

include <lost roam,h>

5:

int main()

6:

8.

213

7:

int localVariable = 5;

8:

int * pLocal= &localVariable;

9:

int * = new int;

10

pHeap = 7;

11

cout << "localVariable: " << localVa

12

cout << "pLocal:

13

cout << "*pHeap:

14

delete ;

15

pHeap = new int;

16

pHeap = 9;

17

cout << "pHeap:

18

delete pHeap;

19

return 0;

20

>

localVariable

<< *pLocal << "\


<< *pHeap "\ n

<< pHeap << \ n

: 5

*pLocal: 5
pHeap: 7
*pHeap: 9


,
( 8). 9 int
. ,
, 7, ,
( 10). ,
.
,
.
.
10, ,
7. 11 12 plocal
. , . , 13,
, , .
, , , 10,
.
, 9,
delete 14.
, .
. 15 16

. 17 ,
.
, 18 ,
.

. ,
.
localVariable.

214



. , , ,
, . .
1;

unsigned short int * pPointer = new unsigned short int;

2;

pPointer

3;

pPointer = new unsigned short int;

4;

pPointer = 84;

= 72;

1
unsigned short int.
72. 3 ,
84 ( 4). ,
72, ,
. ,
.
:
1:

unsigned short int * pPointer = new unsigned short int;

2:

*pPointer

3;

delete pPointer;

4;

pPointer = new unsigned short int;

5;

pPointer = 84;


( 3).

= 72;

new,

delete. ,
,
.



,
. , Cat,
,
, , .
, :
Cat *pCat = new Cat;

new
, .. , . ,
, ,
.

8.

215


delete,
, .
.
, , , .
8.5.
8 . 5 .
1: // 8.5.
2: //

3:
4: include <iostream.h>
5:
6: class SimpleCat
7: <
8:

public:

9:
10:

SimpleCat();
"SimpleCat();

11: private:
12:

int itsAge;

13: >;
14:
15: SimpleCat::SimpleCat()
16: {
17:

cout << "Constructor called.\ n";

18:

itsAge = 1;

19: >

20:
21: SimpleCat::SimpleCat()
22: {

23:
24; }

cout "Destructor called.\ n";

25:
26: int main()
27: <
28:

cout "SimpleCat Frisky...\ n";

29:

SimpleCat Frisky;

30:

cout "SimpleCat *pRags = new SimpleCat..,\ n";

31:

SimpleCat * pRags = new SimpleCat;

32:

cout "delete pRags...\ n";

33:

delete pRags;

34:

cout "Exiting, watch Frisky go...\ n";

35:

return 0;

36: }

216

| ^ ,

SimpleCat Frisky...
. Constructor called.
SimpleCat *pRags = new SimpleCat..
Constructor called.
delete pRags...
Destructor called.
Exiting, watch Frisky go...
Destructor called.

613 SimpleCat. 9,
15-19. 10, 21-24.
29 , .
SimpleCat.
31.
pRags. .
SimpleCat 33
delete pRags. Frisky
.

.s


, ,
(.).
, , ,
. , - GetAge
:
(*pRags).GetAge();

,
GetAge().
.
,
(->).
: . C++
. 8.6
,
.
8 . 6 . _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: // 8.6.
2: //

3:
4: include <iostream.h>
5:
6: class SimpleCat
7: {
8:

public:

8.

217

9:

SimpleCatO { itsAge = 2; }

10:

'SimpleCatO { }

11:

int GetAgeQ const { return itsAge; >

12:

void SetAge(int age) { itsAge = age; }

13:

private:

14:

int itsAge;

15:

};

16:
17:

int main()

18:

19:

SimpleCat * Frisky = new SimpleCat;

20:

cout "Frisky " Frisky->GetAge() << " years old\ n";

21:

Frisky->SetAge(5);

22: cout << "Frisky " << Frisky->GetAge() << " years old\ n";
23:

delete Frisky;

24:

return 0;

25:

'f. . : Frisky 2 years old


Frisky 5 years old

f : 19 .............. SimpleCat. ,
, .
- GetAgeQ, 20.
,
(->). 21
SetAgeQ, GetAge()
( 22) .


,
.
.
, , ( 8.7.).
8 . 7 .
1:

// 8.7.

2:

//

3:
4:

include <iostream.h>

5:
6:

class SimpleCat

7:

8:
9:

218

public:
SimpleCatO;

10:

~SimpleCat();

11:

int GetAge() const { return *itsAge; }

12:

void SetAge(int age) { itsAge = age; }

13:
14:

int GetWeightO const < return itsWeight; }

15:

void setWeight (int weight) { *itsWeight = weight; }

16:
17: private:
18:

int * itsAge:

19:

int * itsWeight;

20: } ;
21:
22: SimpleCat::SimpleCat()
23: {
24:

itsAge = new int(2);

25:

itsWeight = new int(5);

26: }
27:
28: SimpleCat::~SimpleCat()
29: {
30:

delete itsAge;

31:

delete itsWeight;

32: }
33:
34: int main()
35: {
36;

SimpleCat Frisky = new SimpleCat;

37:

cout << "Frisky " << Frisky->GetAge() << " years old\ n";

38:

Frisky->SetAge(5);

39:

cout << "Frisky " << Frisky->GetAge() << " years old\ n";

40: delete Frisky;


41: return 0;
42: }

Frisky 2 years old


Frisky 5 years old

, -
int. ( 2226)
, .
- (
2832).
, .
,
0.
,
( main()), ,
. (GetAgeO
SetAgeQ), .

8.

219

Frisky ( 40)
SimpleCat. , , .

, .


, , , ,
-, ,
, ?

''#iftC.:lude:<iostream.;h>.'
class SimpleCat -

{
" . public

. SlmplsCatO; -

"'>' , Slmi)
, u.jint;G@tAge{) .const..-{return *itsAge; } .

' , //.

i:!: :nt-;::itsAge' : .
' i V; .int::;'*::?!!: sWe

};
SimpleCat '!^',^:1.:

}
.Si^ieCat: :"Sifflg.leCatfpf.v'A'. ..^..V^Wv!..

{
;,

.delete :.itsAge:;; .

}
int mainO

{
.^wySi^RleCatifrisky^1^::;^
:;.7 a cotit'<< "Frisky is; Frisky.GetAgeO << " years old\n";
return 0;

}
Frisky.
,

.
, Frisky
.

, .
.

220

, . ,
. , ,
, ,
.
, ..
.
, , .
, . ,
.
.
9.

this
this.
.
GetAgeO SetAgeO .
8.8 this .
8 . 8 . t h i s _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: // 8.8.
2: // this

3:
4: include <iostrearn. h>

5:
6: class Rectangle
7: {
8

public:

9:

Rectangle();

10

'Rectangle();

11

void

12

int GetLength() const { return this->itsLength; }

SetLength(int

length)

this->itsLength

length;

13
14

void

15

int GetWidth() const { return itsWidth; }

SetWidth(int

width)

itsWidth

width;

16
17

private;

18

int

19

int itsWidth;

itsLength

20; };
21

22

Rectangle;:Rectangle()

23; <
24

itsWidth = 5;

25

itsLength = 10;

26;

27;

RRectangle : :"Rectangle( )

28;

{<

29;

8.

221

30

int main()

31

32

Rectangle theRect;

33

cout << "theRect is

theRect.GetLength()

34

cout << "theRect is

theRect.GetWidth() << " meters wide.\ n"

35

theRect. SetLength(20)

36

theRect.SetWidth(10);

37

cout "theRect is

38

cout "theRect is

39
40

<<

"

meters

long.\

theRect.GetLength()<< " meters long.\


<< theRect.GetWidth()<< " meters wide.\ n;

n"

return 0;
}

theRect is 10 meters long.

theRect is 5 meters wide.


theRect is 20 meters long.
theRect is 10 meters wide.

SetLengthO GetLength()
Rectangle this .
SetWidthO GetWidthO .
, .
this , .
this ,
.
( 10)
this.
, this , ,
.
this .
.
I

,

, . (,
, ) ,
delete 0.
.
.
, .
, .
, .
, - ...
, ,
delete. -
, .
.
, , ,

222

.
.
0.
8.9.
8.9. _________________________
1:

// 8.9.

2:

//

3:

typedef unsigned short int USHORT;

4:

#include <iostream.h>

5:
6:

int main()

7:

8:

USHORT * pint = new USHORT;

9;

pint = 10;

10; cout << "pint: " << *plnt << endl;


11: delete pint;
12:

13: long * pLong = new long;


14: pLong = 90000;
15: cout "*plong: " << *pLong << endl;
16:
17: pint = 20; //
18:
19: cout << "pint: " << pint << endl;
20: cout << "pLong: " << pLong << endl;
21: delete pLong;
22: return 0;
23: }

pint: 10
pLong: 90000
pint: 20
pLong: 65556

( .)
8 pint USHORT.
. 9
10, 10 . ,
pint, delete.
, .
13 (pLong)
new . 14
90000, 15 .
20 , pint, 20. ,
,
.
.

8.

223

19 pint . ,
, 20. 20 pLong. ,
, 65556. .
1. pLong, ?
2. 20, 17?
, , , . 17
20 , pint. ,
11,
. pLong ( 13)
, pint. ,
. 20 ,
pint, pLong, .
.
,
.
pint pLong.
.
, plong
65556.

1. pint , 10.
2.

delete
. pLong.

3.

*pLong 90000.
long ,
90000 (00 01 5F 90) 5F 90 00 01.

4.

pint 20, 00 14
.
, 90000 .
00 14 00 01.
5. Long 00
01 00 14, 65556.

delete

, .

new

delete.

new.

224


?
delete,

, ,
, .

myPtr

0:, .

delete,
, . ,
.

(.. myPtr = 5) ,
,
.

const

const
. , ,
:
const int * pOne;
int * const pTwo;
const int * const pThree;

pOne int.
, , .
pTwo int.
, , ,
.
, pThree int.
, ,
, .
,
. const,
, . const
, .
const int

* pi; //

ini

int * const 2: // ,

8,

225

const
-
4 const
- .
.
,
, const ( 8.10).

8.10. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: // 8.10.
2: //

3:
4: include <iostream.h>
5:
6: class Rectangle
7: {
8

public:

9:

Rectangle();

10
11

void

12

int

13

void

14

int GetWidth() const { return itsWidth; }

"Rectangle();
SetLength(int
GetLength()
SetWidth(mt

length)

const
width)

itsLength

return
{

itsLength;

itsWidth-

length;

width:

15
16

private :

17

int

18

int itsWidth;

itsLength;

19

20
21

Rectangle::Rectangle()

22
23

itsWidth

24

itsLength = 10;

5;,

25
26
27

Rectangle : :~Rectangle( )

28
29
30

int main( )

31
32

Rectangle* pRect = new Rectangle;

33

const Rectangle * pConstRect = new Rectangle;

34

Rectangle * const pConstPtr = new Rectangle;

35
36

cout << "pRect width: " << pRect->GetWidth() << " meters\ n";

37

cout << "pConstRect width: " << pConstRect-> GetWidth() << " meters\ n";

38

cout << "pConstPtr width: " << pConstPtr-> GetWidth() << " meters\ n";

226

39:
40:

pRect->SetWidth(10) ;

41:

// pConstRect->SetWidth(10);

42:

pConstPtr->SetWidth(10);

43:
44:

cout << "pRect width: " << pRect->GetWidth() << " meters\ n";

45:

cout<< "pConstRect width:" pConstRect->GetWidth() << " meters\ n";

46:

cout << "pConstPtr width: "<< pConstPtr->GetWidth() << " meters\ n";

47:

return 0;

48:

pRect width: 5 meters


pConstRect width: 5 meters
pConstPtr width: 5 meters
pRect width: 10 meters
pConstRect width: 5 meters
pConstPtr width: 10 meters

619 Rectangle. ,
GetWidth(), 14, const.
32 Rectangle, 33
. pConstPrt 34.
3638 .
SetWidth(), pRect ( 40),
. 41 pConstRect
. , pConstRect ,
const ,
. 42 SetWidth( ) pConstPrt.
,
, .

mallocQ.

,
,

const

,
.

,
.

const this
this
. , const this
, const.

.

8.

227


. , ,
,
, .

( 8.11).

8 . 1 1 .

1:

#include <iostream.h>

2:

include <ctype.h>

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

3:

include <string.h>

4:

bool GetWord(char* string, char* word, int& wordOffset);

5:

//

6:

int main()

7
const int bufferSize = 255;
9:

char buffer'[bufferSize+1 ];

//

10

char word[bufferSize+1 ];

//

11

int wordOffset = 0;

//

12
13

cout << "Enter a string: ":

14

ein. getline(buffg,bufferSize);

15
16

while (GetWord(buffer,word,wordOffset))

17
18

cout << "Got this word: " << word << endl:

19
20

21

return 0;

22

23
24
25
26

// ,

27

bool GetWord(char* string, char* word, int& wordOffset)

28
29
30

if (Istring[wordOffset]) // ?

31

return false;

32
33
34

char *p1, *p2;


p1 = p2 = string+wordOffset;

//

35
36

//

37

for (int i = 0; i<(int)strlcn(p1) && ! isalnuin(p1[0]); i++)

38

p1++;

39

228

<10;

//

41:

if (11(1[0]))

42;

return false;

43;
44;

// 1 !

45:

// i 2

46;

2 " |)1;

47;
48;

// 2

49;

while (isalnum(p2[0]))

50;

2++;

51;
62;

// 2

53:

// 1 -

54;

//

55:

int len = int (2 - 1);

56:
57:

//

58:

strncpy (word,1,len);

59:
60:

//

61:

word[len]=1\ O' ;

62:
63:

//

64:

for (int i = int(p2-string); i<(int)strlen(string) && !isalnum(p2[0]); i++)

65: p2++;
66;
67:

wordOffset = int(p2-string);

68:
69:

return true;

70:

Enter a string: this code first appeared in C++ Report


Got

this

word:

this

Got

this

word:

code

Got

this

word:

first

Got

this

word:

Got

this

word:

in

Got

this

word:

appeared

Got this word: Report

13 .
GetWord(),

WordOffset. 11 WordOHset 0.
( GetWordO 0)
.

8.

229

GetWordO 27. ,
30, st ng [ wo rdOffset] .
, . GetWordO
false.
33 . 34
,
WordOffset. WordOffset 0, .
37 38 1 ,
. ,
false ( 41 42).
, 1 . 46
2 .
49 50 ,
, . 2 . 1 2
. 2
1 .
( 55).
.
61 ,
. 2 ,
WordOffset
. true, ,
.
,
, ,
.

.
, (&).
.
,
, .
. ,
0.
, ,
(*). .
. ,
, .
- ,
new, .
delete.
,
, .

230

,
. 13
.
?
, ,
, . ,
,
. .
, ?
, .
,
. const .


, ,
.
, .
,
.


1. ?
2. , ,
?
3. ?
4. , , ,
?
5. ?
6. : const

int * ptrOne

int * const

ptrTwo?

1. :

int *

int vTwo

int * pThree = &vTwo

8.

231

2.

, youiAge unsigned
, ?

short.

3. you f Age 50.


, int
. . ,
- ,
5. : .

4.

((include <i ost: earn, h>


int mainQ

{
int * pint;
pint = 9;
cout "The value at pint: " << * pint;
return 0;

}
6. : .
int main()

{
int SomeVaiable = 5;
cout << "SomeVariable: " << SomeVariable << "\ n";
int *pVar = & SomeVariable;
pVar = 9;
cout << "SomeVariable: " << *pVar << "\ n";
return 0;

232

,
.
, ,
, , . :


, .
, .
, , ,
.
,
(&), .
,
. ,
somelnt, ,
int &rSomeRef = somelnt:

: rSomeRef
, somelnt.
9.1.
, (&) ,
,
. ,
, .

9.

233

8 . 1 .
1:
2:

// 9.1.
//

3:
4:

include <iostream.h>

5:
6:

int main()

7:
8:

{
int intOne;

9:

int &rSomeRef = intOne;

10 :
11:

intOne = 5;

12:

cout << "intOne: " << intOne << endl;

13:

cout << "rSomeRef: " << rSomeRef endl;

14:
15:

rSomeRef = 7;

16:

cout << "intOne: " << intOne << endl;

17:
18:

cout << "rSomeRef: " << rSomeRef << endl;


return 0;

19:

>

^:

^
1:

5
7

^ 7

8 ,
9 rSomeRef ,
^. , ,
. , ,
.
11 ^ 5. 12 13
^ , ,
.
15 rSomeRef 7.
, ^, 7
^,
16 17.

(&)

, .
. .
9.2.

234

9.Z.
1: // 9.2.
2: //

3:
4: ((include <iostream. h>
5:
6: int main()
7: {
8:

int intOne;

9:

int &rSoneRef = intOne;

10:

11:

intOne = 5;

12:

cout << "intOne: " << intOne << endl;

13:

cout << "rSomeRef: " << rSomeRef << endl;

14:
15:

cout << "&i.ntOne: " << &intOne << endl;

16:

cout << "&rSomeRef: " << &rSomeRef << endl;

17:
18: return 0;
19: }

intOne: 5
rSomeRef: 5
&intOne: 0x3500
&rSomeRef: 0x3500

- rSomeRef

,
. C++
, .
.
, ,
, .
, City,
:
intOne.

City boston;

City
, :
City SbeanTown = boston;

9.

235

City;
. ,
beanTown, boston.
& 9 9.2,
rSomeRef int, &
15 16, intOne
rSomeRef.
.
, 13.


, ,
,
. ,
, .
9.3.

8.3. ___________________________________________
1:

// 9.3.

2:

//

3
4

((include ciostream.h>

int main()

int intOne;

9:

int &rSomeRef = intOne;

10 :

11:

intOne = 5;

12:

cout << "int0ne:\ t" << intOne << endl;

13:

cout << "rSomeRef:\ t" << rSomeRef << endl;

14:

cout << "&int0ne:\ t" << &int0ne << endl;

15:

cout << "&rSomoRef:\ t" << &rSomeRef << endl;

16:
17:

int intTwo = 8;

18:

rSomeRef = intTwo; // !

19:

cout << "\ nintOne:\ t" << intOne << endl;

20:
21:
22:

cout << "intTwo:\ t" << intTwo << endl;


cout << "rSomeRef:\ t" << rSomeRef << endl;
cout << "&int0ne:\ t" << &int0ne << endl;

23:

cout << "&intTwo:\ t" << &intTwo << endl;

24;

cout << "&rSomeRef:\ t" << &rSomeRof << endl;

25:

return 0;

26:

236

intOne:

rSomeRef;

intOne:

0x213e
0x213e

intOne:

intTwo:

rSomeRef:

&intOne:

CO

&rSomeRef:

&intTwo:

0x2130

&rSomeRef:

0x213e

8 9
. 11
5, 1215 , .
17 11:,
8. 18 !^ ,
, .
!^ 110,
:
10 = .;

,
!^ ( 19 21):
].1:\. 2224
, ^ ^,
11:\.


.
.

.

.


, (
) . , ,
. :
int & In tRef = int; //

rlntRef
, :

int howBig = 200:


int & rlntRef = howBig;

CAT:
CAT & rCatRef = CAT; //

9.

237

rCatRef

CAT:

CAT frisky;
CAT & rCatRef = frisky;

, . -
( . ) , , ,
. 9.4.

9.4. _____________________________________________
1: // 9.4.
2: //

3:
4: include <iostream.h>
5:
6: class SimpleCat
7: {

public

9:

SimpleCat (int age, int weight);

10

~SimpleCat() { }

11

int

12

int GetWeightO { return itsWeight; }

13

return

itsAge;

private:

14

int itsAge;

15
16:

GetAge()

int itsWeight;
} ;

17:
18:

Sim
SimpleCat::SimpleCat(int age, int weight)

19:

20

itsAge = age;

21

22:

itsWeight = weight;

23:
24:

int main()

25:

26

SimpleCat Frisky(5,3);

27

SimpleCat & rCat = Frisky;

28
29

cout << "Frisky: ";

30

cout << Frisky.GetAge() << " years old. \ n;

31

cout " Frisky : ";

32

cout << rCat. GetWeight() << " kilograms. \ n>>;

33

return 0;

34

Frisky: 5 years old.


Frisky : 3 kilograms.

238

26 Frisky
27 rCat
SimpleCat,
Frisky. 30 32 SimpleCat,
SimpleCat (Frisky),
SimpleCat (rCat). , .
: .
SimpleCat.

,
(&) . .
1:
int

hisAge;

int &rAge'= hisAge;

2:
CAT boots;
CAT &rCatRef = boots;


,
(0). .
, , ,
.
. ,
- .
,
, -
. ,
.


5 , :
,
.

. ++ :
. :
, , .

, . ,
, .

9.

239

5 , , ,
. ( ,
), , .

, . ,
,
, .
,
.
, 5.5 (. 5) ,
1() .
- ( 9.5).

8.5.
1; // 9.5.
2:
3:

include <iostream.h>

4:
5:

void swap(int x, int y);

6:
7: int main()

8
9:

int x = 5, = 10;

10
11

cout << "Main. Before swap, x: " << x << " ; " << << "\ n";

12

swap(x,y);

13

cout << "Main. After swap, x: << x << " : " << << "\ n";

14

return 0;

15
16
17

void swap (int x, int y)

18
19

int temp;

20
21

cout << "Swap. Before swap, x: " << x << " : " << << "\ n";

22
23

temp = x;

24

x = y;
= temp;

25
26
27

cout: << "Swap. After swap, x;

x " :

" << << "\ n";

28
29

Main. Before swap, x: 5 y: 10


Swap. Before swap, x: 5 y: 10
Swap. After swap, x: 10 y: 5
Main. After swap, x: 5 y: 10

240

!(),
, , , .
() ,
.
, ()
, ..
. , .
++ :
8\</()
.

! swap[]
, , ,
, .
swap() ,
, .

. 9.6.

8.. ______________________
1:

// 9.6.

2
3

(finclude <iostream. h>

4
5

void swap(int *, int *y);

6
7

8
9:

10
11
12
13
14

int x = 5, = 10;
cout << "Main. Before swap, x: " << x << " : " << << "\ n";
swap(&x,&y);
cout << "Main. After swap, x: " << x << " : " << << "\ n";
return 0;

15
16
17

void swap (int *px, int *py)

18
19

int temp;

20
21

cout << "Swap. Before swap, *px: " << *px << " *py: " << *py << "\ n";

22
23

temp = *px;

24

*px = *py;

25

*py = temp;

26
27

cout << "Swap. After swap, *px: " << *px << " *py: " << *py << "\ n"

28
29

9.

241

Main. Before swap, x: 5 y: 10


Swap. Before swap, *px: 5 *py: 10
Swap. After swap, *px: 10 *py: 5
Main. After swap, x: 10 y: 5

! 5 swapQ
int,
int. 12 swap()
.
19 swap() temp,
: * (..
) .
temp .
23 temp , .
24 , , .
25 , temp (.. ,
), .
,
swap(), .

swap))
, , ,
. -,
swap()
, , . -,

swap().
C++
.
,
.
9.7, swapQ .
swap()

9.7. s w a p ( ) , ________________________
1:

// 9.7. -.

2:

// !

3
4

include <iostream.h>

void swap(int &, int &);

int main()

9:
10

int x = 5, = 10;

11

12

cout << "Main. Before swap, x: " << x << " : " << << "\ n";

13

swap(x,y);

14

cout << "Main. After swap, x: " << x << " : " << << "\ n";

242

15

return 0;

16
17
18

void swap (int &rx, int &ry)

19
int temp;

20
21

cout << "Swap. Before swap, rx: " << rx " ry: " << ry << "\ n";

22
23
24

temp = rx;

25

rx = ry;

26

ry = temp;

27
28

cout << "Swap. After swap, rx: " << rx << " ry: " ry << "\ n";

29

30
Main. Before swap, x:5 y: 10
Swap.

Before

Swap.

After swap, rx:10 ry:5

swap, rx:5 ry:10

Main. After swap, x:10, y:5

, , 10
, 12. 13 swap(), ,
, . .
swap() 18,
.
22, , ,
.
2426 ,
28. ,
14 , ().
swap() , ()
, , ().
,
,
!


9.6 swap(),
, 9.7 , .
, , ,
, ,
? (
) \(), ,
swap() .

9.

243

,
. , ,
,
, , swapO,
, , .
swapO - , ,
, .
C++
.
, .
,
.
(Colonel John Roebling)
(Brooklyn Bridge),
. ,
.
,
.
C++
, .
,
, , , .
, ,
, , .,
, ,
, .


, .
, ?
.
. ,
,
. ,
( ) .
, ,
. 9.8 , :
- .

.8. _____________________________ _
1:

// 9,8,

2:

//

3:
4:

include <iostream.h>

5:

int

6:

short Factor(int n, int* pSquared, int* pCubed);

7:
8:

int tnain()

9:

244

10:

int number, squared, cubed;

11:

short error;

12:

13:

cout << "Enter a number (0 - 20): ";

14:

cin >> number;

15:
16:

error = Factor(number, &squared, &cubed);

17:
18:

if (!error)

19:

20:

cout << "number: " << number << "\ n";

21:

cout << "square: " << squared << "\ n";

22:

cout << "cubed: " << cubed "\ n";

23:

24:

else

25:
26:

cout << "Error encountered!!\ n";


return 0;

27: }
28:
29: short Factor(int n, int pSquared, int *pCubed)
30: {
31: short Value = 0;
32:

if (n > 20)

33:

Value = 1;

34:

else

35:

36:

*pSquared = n*n;

37;

pCubed = n*n*n;

38:

Value = 0;

39:

40:

return Value;

41: }

Enter a number (0-20): 3


number: 3
square: 9
cubed: 27

10 number, squared cubed


int. number ,
. , squared cubed
Factor () .
FactorO , .
20 ( , ),
Value ,
. , FactorO
1, 0, ,
, , 40.

9.

245

, ( )
,
, .
36 37 main()
. 38 Value
, . 40
Value .
,
:
enum ERR0R_VALUE { SUCCESS, FAILURE} ;

SUCCESS

FAILURE.


9.8 ,
, , .
9.9 ,
,
ERROR.

3.9. _________________________________
1 :

// 9.9,

2:

//

3:

//

4
5

include <iostream.h>

typedef unsigned short USHORT;

enum ERR_C0DE < SUCCESS, ERROR }

9:

10

ERR_C0DE Factor(USH0RT, USH0RT&, USH0RT&);

11
12

int main()

13
14

USHORT number, squared, cubed;

15

ERR_C0DE result;

16
17

cout << "Enter a number (0 - 20)

18

cin >> number;

19

20
21

result = Factor(number, squared, cubed);

22

if (result == SUCCESS)

23
24

cout << "number: " << number << "\ n";

25

cout << "square: " << squared << "\ n";

26

cout << "cubed: " << cubed "\ n";

246

27:

28:

else

29:

cout "Error encountered!!\ n";

30: return 0;
31: }
32:
33: ERR_C0DE Factor(USH0RT n, USHORT &rSquared, USHORT &rCubed)
34: {
35:

if (n > 20)

36:

return ERROR; // simple error code

37:

else

38:

39:

rSquared = n*n;

40:

rCubed = n*n*n;

41:
42:

return SUCCESS;
}

43: >

Enter a number (0 - 20): 3


number: 3
square: 9
cubed: 27

9.9 9.8 .
ERR C0DE (. 36
41), , , ( 22).
Factor().
, squared cubed,
.




. .
5 ,
. ,
, .
, ,
. -. - , ,
,
, .
, .
-. , -

9.

247

-, ,
- ,
.
,
, .
, , .


. 9.10
SimpleCat.
, , ,
- .
, 9.10 SimpleCat,
. Cat ,
. , ,
.

3.10. _________________________
1 : // 9.10.
2: //
3:
4: include <iostream.h>
5:
6: class SimpleCat
7: {
8: public:
9:

SimpleCat ();

10:

SimpleCat(SimpleCat&); // -

//

11:

"SimpleCatO;

//

12:}:
13:
14: SimpleCat::SimpleCat()
15: {
16:

cout << "Simple Cat Constructor...\n";

17: }
18:
19: SimpleCat::SimpleCat(SimpleCat&)
20: {
21:

cout << "Simple Cat Copy Constructor...\ n";

22: }
23:
24: SimpleCat::"SimpleCat( )
25: {
26:

cout << "Simple Cat Destructor..,\ n";

27: }
28:
29: SimpleCat FunctionOne (SimpleCat theCat);
30: SimpleCat* FunctionTwo (SimpleCat *theCat);
31 :
32: int main()

248

33: {

34:

cout "Making

35:

SimpleCat Frisky;

36:

cout "Calling FunctionOno...\ n";

cat...\ n";

37;

FunetionOna(Frisky);

38:

cout << "Calling FundionTwo.. ,\ n";

30:

FunctionTwo(&Frisky);

40: return 0;

41: }
42:
43: // FunctionOne,
44: SimpleCat FunationOne(Simp 1eCat theCat)
45: {
46:
cout "Function One, Returning,
47:
return theCat;
48: }
49:
50: // FunctionTwo,
51: SimpleCat* FunctionTwo (SimpleCat *theCat)

,,\ ri";

52: <
53:

cout << "Function Two. Returning..,\ n";

54:

return theCat;

55: }

Making a cat...
Simple Cat Constructor...
Calling FunctionOne...
Simple Cat Copy Constructor...
Function One. Returning...
Simple Cat Copy Constructor...
Simple Cat Destructor...
Simple Cat Destructor...
Calling FunctionTwo...
Function Two. Returning...
Simple Cat Destructor...

.
.

6~12 .
, -
, ,
.
34 ( ) ,
. 35
. , ,
( 2 ).

9.

249

36 main() FunctionOne,
( 3 ).
FunctionOne() SimpleCat ,
SimpleCat .
,
( 4).
46,
, ( 5
).
, SimpleCat .
- , ,
( 6 ).
, FunctionOne(),
, ,
, , ,
, 7
. FunctionOneO ,
,
, 8 .
main(),
FunctionTwo(), .
, . FunctionTwoO , 10
, SimpleCat
( ), .
Frisky ,
, ( 11
).
, ,
FunctionOne()
, ,
FunctionTwoO .


FunctionTwoO ,
, .
FunctionTwoO ,
SimpleCat, SimpleCat.
,
.

. - ,
.

.
,
SimpleCat.
, SimpleCat.
9.11.

250

9.11. ____________________________
1:

// 9.11.

2:

//

3:
4:

include <iostream.h>

5:
6:

class SimpleCat

7:

8:

public:

9:

SimpleCatO;

10:

SimpleCat(SimpleCat&);

11:

'SimpleCatO;

12:

13:

int GetAgeO const { return itsAge; }

14:

void SetAge(int age) { itsAge = age; }

15:
16:

private:

17:

int itsAge;

18: > ;
19:
20:

SimpleCat::SimpleCat()

21: {
22:

cout "Simple Cat Constructor...\n";

23:

itsAge = 1;

24:

25:
26:

SimpleCat::SimpleCat(SimpleCat&)

27:

28:

cout << "Simple Cat Copy Constructor..,\n";

29:

30:
31:

SimpleCat::~SimpleCat()

32:

33:

cout << "Simple Cat Destructor...\n";

34:

35:
36:

const

SimpleCat

const

FunctionTwo

(const

SimpleCat

const

theCat);

37:
38:

int main()

39:

40:

cout "Making a cat...\ n";

41:

SimpleCat Frisky;

42:

cout "Frisky is " ;

43

cout << Frisky.GetAge();

44:

cout " years old\ n";

45:

int age = 5;

46:

Frisky.SetAge(age);

47:

cout "Frisky is " ;

48

cout Frisky.GetAge();

9.

251

49:

cout << " years ol(i\ n";

50:

cout << "Calling FunctionTwo,\ n";

51:

FunctionTwo(&F:risky) ;

52:

cout "Frisky is " :

53:

cout Frisky, GotAgeO;

54:

cout " years _old\ n":

55: return 0
56:

57:
58: // functionTwo, passes a const pointer
59: const SimpleCat * const FunctionTwo (const SinipleGat * const theCat)
60: {

61:

cout "Function Two, Returning,..\ n";

62:

cout "Frisky is now " theCat->GetAge();

63:

cout << " years old \ n";

64:

// theCat->SotAge(8): const!

65:

return theCat:

66: }
Making a cat,,,
Simple Cat constructor.,.
Frisky is 1 years old
Frisky is 5 years old
Calling FunctionTwo...
FunctionTwo. Returning...
Frisky is now 5 years old
Frisky is 5 years old
Simple Cat Destructor...
r

- SimpleCat :
GetAgeO ( 13), ,
SetAgeO ( 14), .
- itsAge ( 17).
, - -
. -
,
. 41 ,
. 42.
46 itsAge Set ,
47.
FunctionOne , FunctionTwoO,
. 36. ,
.
, ,
- .
FunctionTwoO , ,
SetAge().
SetAgeO 64 ,
.

252

, , main(),
Frisky SetAge().
FunctionTwoO, ,
FunctionTwoO ,
, ,
!


, 9.11,
,
, .
,
. -
,
.
, , ,
, .
9.12.

3.12.
1: // 9.12.

2: //
3:
4: include <iostream.h>
5:
6: class SimpleCat
7: {
8: public:
9:

SimpleCat();

10:

SimpleCat(SimpleCat&);

11:

"SimpleCat();

12:

13:

int GetAge() const { return itsAge; >

14:
15:

void SetAge(int age) { itsAge = age: }

16: private:
17:

int itsAge;

18: } ;
19:
20: SimpleCat::SimpleCat()

21: {
22:

cout << "Simple Cat Constructor..,\n";

23:

itsAge = 1;

24: }
25:
26: SimpleCat::SimploCat(Si mploCat&)
27: {
28:

9.

cout "Simple Cat Copy Constructor,.,\n";

253

29: }
30:
31: SimpleCat::~SimpleCat()
32: {
33:
34:

cout << "Simple Cat Destructor...\n;


>

35:
36:

const SimpleCat & FunctionTwo (const SimpleCat & theCat);

37:
38: int main()
39: {
40:

cout << "Making a cat...\ n";

41:

SimpleCat Frisky;

42:

cout << "Frisky is " << Frisky.GetAge() << " years old\ n";

43:

int age = 5;

44:

Frisky,SetAge(age);

45:

cout << "Frisky is " << Frisky.GetAge() << " years old\ n";

46:

cout << "Calling FunctionTwo...\ n";

47:

FunctionTwo(Frisky);

48:

cout << "Frisky is " << Frisky.GetAge() << " years old\ n";

49: return 0;
50:

51:
52:

// functionTwo, passes a ref to a const object

53:

const SimpleCat & FunctionTwo (const SimpleCat & theCat)

54:

55:

cout << "Function Two. Returning...\ n";

56:

cout << "Frisky is now " << theCat. GetAgeO;

57:

cout << " years old \ n";

58:

// theCat.SetAge(8); const!

59:

return theCat;

60: }

Making a cat...
Simple Cat constructor...
Frisky is 1 years old
Frisky is 5 years old
Calling FunctionTwo...
FunctionTwo. Returning...
Frisky is now 5 years old
Frisky is 5 years old
Simple Cat Destructor...

,
9.11.
FunctionTwo() .
- , ,
,
const.

254


, C++,
SimpleCat SimpleCat.
, ,
. const,
, .

,
-
,
. ,
, .
.
, , .
, , - ,
, .
.
new. new
, .
, ,
, . , :
int * pint = new int;
if (pint != NULL)
int &rlnt = pint;

pint int,
, new.
( pint) , , null, pint
. int
int, rlnt . ,
rlnt int, new.


, .

, .
const
,
.

9.

,
.

.

255


,
, , , :
CAT * SomeFunction (Person &theOwner, House *theHouse, int age);

, SomeFunction .
Person,
House, .
CAT.
,
(&)
(*). :
1: & rFrisky;

2: CAT

& rFrisky;

3: CAT &rFrisky;]

C++
, , ,
, .
,
, . ,
.
. rFrisky
rFrisky,
CAT. ,
& .
. CAT . &
, .
, & CAT
:
& rFrisky, rBoots;

,
rFrisky, rBoots
CAT. .
, rFrisky CAT,
rBoots ( )
, CAT.
-:
CAT &rFrisky, rBoots;

,

. :
& rFrisky;
CAT Boots;

256

,
, , ,
(, , ),
2:

2: CAT

& rFrisky;

, (&)
(*).
, ,
,
.

.
1.

,
.

2.

,
.

,
!
,
. , . ,
.
: ,
,
?
9.13 ,
, .

9.13.
1:

_______

// 9.13.

2:

// ,

3:

//

4:
5:

include <iostream.h>

6:
7:

class SimpleCat

8:

9:

public:

10:
11:

SimpleCat (int age, int weight);


'SimpleCat() { }

12:

int GetAge() { return itsAge; }

13:
14:

int GetWeight() { return itsWeight; }


private:

9.

257

15:

int itsAge;

16:

int itsWeight;

17: > ;
18:
19: SimpleCat::SimpleCat(int age, int weight)

20: {
21:

itsAge = age;

22:

itsWeight = weight;

23: }
24:
25: SimpleCat &TheFunction();
26:
27: int main()
28: {
29:

SimpleCat &rCat = TheFunction();

30:

int age = rCat.GetAge();

31:

cout "rCat " << age " years old!\n";

32: return 0;
33: }
34:
35:

SimpleCat &TheFunction()

36:

37:

SimpleCat Frisky(5,9);

38:

return Frisky;

39: }

Compile error: Attempting to return a reference to a local object! (


"

: !)

Borland,
Microsoft.

.

717 SimpleCat. 29
SimpleCat
TheFunction(), 25.
SimpleCat.
TheFunction() SimpleCat
. .
,
, . (
, )
.
TheFunctionQ Frisky
(, ). ,
, , .

258



, 9.13,
TheFunctionO Frisky
. TheFunctionO
Frisky .
: ,
Frisky, ?
9.14.

.14.
1: // 9.14.

2: //
3: include <iostream.h>
4:
5:

class SimpleCat

6: {
7:

public:

8:

SimpleCat (int age, int weight);

9:

"SimpleCatO { }

10:

int GetAgeO { return itsAge; >

11:

int GetWeightO { return itsWeight; }

12:
13 private:
14:

int itsAge;

15:

int itsWeight;

16: } ;
17:

18:

SimpleCat::SimpleCat(int age, int weight)

19: {

20:

itsAge = age;

21:

itsWeight = weight;

22: }
23:
24: SimpleCat & TheFunctionO;
25:
26; int main()
27: {

28:

SimpleCat & rCat = TheFunctionO;

29:

int age = rCat.GetAgeO;

30:

cout "rCat " age << " years old!\n";

31:

cout "&rCat: << &rCat << endl;

32:

// ?

33;

SimpleCat * pCat = &rCat;

34:

delete pCat;

9.

259

35:

// , rCat??

36: return 0;
37: }
38:
39:

SimpleCat &TheFunction()

40:

41:

SimpleCat * pFrisky = new SimpleCat(5,9);

42:

cout << "pFrisky: " << pFrisky << endl;

43:
44:

return pFrisky;
}

pFrisky: 0x00431C60
rCat 5 years old!
&rCat: Ox00431C60

, , , .
.

. () ,
. 41
.
, 11
.
28 ()
,
, 30.
, , (), ,
,
(), (&).
, , , ,
.
. ,
? .
: ,
:. ,
. :
34? ,
;
( ), .
^0**..... . ---

260

,
(
),
.

.
SimpleCat 28 TheFunction
. SimpleCat (
TheFunction()), , TheFunction()
. , ,
delete.
(, )
, TheFunction()ccbuiKy .

?

. ,
, .
, , ,
, .
,
. , .
,
, .
:
delete
.
. ,
, .
,
, ,
. ,
. ,
, , .

,
.
I
-1
,
.

,

.

.

,
. ,
.
, , ,
. ,
.

9.

261

,
, .
.
, , , ,
,
, .

,
, .


, ?

, .
,
.
, ?

, .
, .
?

, ,
,
.
,
?


,
.


, ,
. ,
.
,
.


1. ?
2. , ?
3. new, ?
4. ?

5. ?

262


1. , int,
int int.
int.
2. ,
. ,
varOne. varOne 6.
, varOne 7.
varTwo. ,
varTwo. .
3. , 2.
? ?
4. , .
5. 4, .
6. , .
7. 6.
8. : ?
1: include <iostream.h>

2:
3: class CAT
4: {
5:

public:

6:

CAT(int age) { itsAge = age; }

7:

CAT(){ >

8:

int GetAge() const { return itsAge;}

9:

private:

10:
11:
12:

int itsAge;
) ;

13: CAT & MakeCat(int age);


14: int main()
15: {
16:

int age = 7;

17;

CAT Boots = MakeCat(age);

18;

cout "Boots is " Boots.GetAgeO " years old!\n";

19;

return 0;

20: }
21:
22: CAT & MakeCat(int age)
23: {
24:
25;

CAT * pCat = new CAT(age);


return *pCat;

26: }
9. 8.

9.

263



5
. , , ,
. :

-
5 ,
.
. - .
Rectangle ( 10.1) DrawShape(). ,
, ,
.
, .

10.1. -___________________________________________
1:

// 10.1. -

2:

((include <iostream.h>

3:
4:

int

5:

// Rectangle

6:

class Rectangle

7:

264

8: public:
9:

//

10: Rectangle(int width, int height):

11: 'Rectangle(){ }
12:
13:

// - DrawShape

14: void DrawShape() const;


15: void DrawShape(int aWidth, int aHeight) const;
16:
17: private:
18: int itsWidth;
19: int itsHeight;

20: } ;
21:
22: //
23: Rectangle::Rectangle(int width, int height)
24: {
25: itsWidth = width;
26: itsHeight = height;
27: }
28:
29:
30: // DrawShape -
31: // ,
32: void Rectangle::DrawShape() const
33: {
34: DrawShape( itsWidth, itsHeight);
35: >
36:
37:
38: // DrawShape -
39: // ,
40: void Rectangle::DrawShape(int width, int height) const
41: {
42: for (int i = 0; i<height; i++)
43: {
44:

for (int j = 0; j< width; j++)

45:

46:

cout << "*";

47:

48:

cout "\n;

49: >
50; }
51:
52:

//

53: int main()


54: {
55:

// 30 5

56: Rectangle theRect(30,5);


57: cout << "DrawShape(): \n";

10.

58: theRect. DrawShapeO;


59:

cout

''\nDrawShape(40,

2):

\n";

60: theRect.DrawShape(40,2);
61:

return 0;

62:

>

******************************
******************************
DrawShape(40,2):

************************************************************
************************************************************
10.1 , .
,
.
.
14 15,
DrawShapeO. ,
30 50. , DrawShapeO
, ,
-.
.
,
.
52 62
DrawShapeO. ,
unsigned short integer.

.
DrawShapeO,
, ,
.

,
- , ,
, . - ,
, ,
10.2

266

1B.Z. ,
1: // 10.2. ,
2: ((include <iostream.h>

3:
4: int
5:
6: // Rectangle
7: class Rectangle

8: {
9: public:
10:

//

11: Rectangle(int width, int height);


12: "Rectangle( ) { }
13: void DrawShape(int aWidth, int aHeight, bool UseCurrentVals = false) const;
14:
15: private:
16: int itsWidth;
17:

int itsHeight;

18: } ;
19:
20: //
21: Rectangle::Rectangle(int width, int height):
22: itsWidth(width),

//

23: itsHeight(height)
24: < }

//

25:
26:
27: //
28: void Rectangle::DrawShape(
29: int width,
30: int height,
31:

bool UseCurrentValue

32: ) const
33: {
34:

int printWidth;

35: int printHeight;


36:
37:

if (UseCurrentValue == true)

38: {
39:

printWidth = itsWidth;

40:

printHeight = itsHeight;

41

//

:}'.'

42: else
43: <
44:

printWidth = width;

45:

printHeight = height;

//

46: >
47:
48:

10.

267

for (int i = 0; i<printHeight; i++)

49:
50:

51:

for (int j = 0; j< printWidth; j++)

52:

53:

cout

54:

55:

cout "\n";

56:

57:

58:
59://
60:

int main()

61:

62:

// 30 5

63:

Rectangle theRect(30,5);

64:

cout << "DrawShape(0,0,true)...\n";

65:

theRect.DrawShape(0,0,true);

66:

cout <<"DrawShape(40,2)...\n";

67:
68:

theRect.DrawShape(40,2);
return 0;

69:

DrawShape(0,0,true).

*******

DrawShape(40,2)...
A***********************************************************

************************************************************

10.2 DrawShapeQ
, .
13 . , aWidth aHeigth, USH0RT,
UseCurrentVals,
false.
28.
UseCurrentVals.
true, printWidth
printHeigth - itsWidth itsHeigth.
, UseCurrentVals false
, , ,
printWidth printHeigth ,
.
, UseCurrentVals ,
.

268



10.1 10.2 ,
10.1
. , ,
, ,
, ,
.
,
? .
, :

,
;

;
, .

,
, , ,
,
.
, ,
,
.
, ,
.
, . ,
,
.
, - ,
. ,
, ,
!


. ,
Rectangle .
.
.
.

10.

269

, , .
.
, Rectangle .
,
.
10.3.

10.3. ____________________________ _________________


1 : // 10.3.
2: //

3:
4: include <iostream.h>
5:
6: class Rectangle
7: {

public:
RectangleO;
Rectangle(int width, int length);

9:

10
11

"RectangleO { >

12

int GetWidthO const < return itsWidth; }


int GetLength() const { return itsLength; }

13
14

private:
int itsWidth;

15

int itsLength;

16
17

18
19

20
21
22

Rectangle::Rectangle()
itsWidth = 5;
itsLength = 10;

23
24
25

Rectangle:: Rectangle (int width, int length)

26
27

itsWidth = width;

28

itsLength = length;

29
30
31

int main()

32
33

Rectangle Recti;

34

cout "Recti width: " Recti.GetWidth() endl;

35

cout "Recti length: " Recti.GetLength() endl;

36
37

int aWidth, aLength;

38

cout << "Enter a width:

39

cin aWidth;

40

cout << \ nEnter a length:

41

cin aLength;

42

270

43

Rectangle Rect2(aWidth, alength);

44

cout

45

cout Rect2 length: " Rect2.GetLength() endl;

46

"\

nRect2

width:

"

Rect2.GetWidth()

endl;

return 0;

47

Recti width: 5
Recti

length:

10

Enter a width: 20
Enter a length: 50
Rect2 width: 20
Rect2 length: 50

Rectangle 6 17.
: ( 9), ( 10). 33
.
, , 34 35. 37
41
. 43 ,
. ,
, , 44 45.
,
, .


- .
:
.
:
, .
, , -
.
-:
CAT():

//

itsAge(5), //
itsWeigth(8)
{}

//

.
-.
.
, .
10.4 ,
10.3.
.

10.

271

10.4. -
1: Rectangle : :Rectangle():
2: itsWidth(5),
3: itsLength(IO)
4: <
5: }

6:
7: Rectangle::Rectangle (int width, int length):
8:

itsWidth(width),

9:

itsLength(length)

10 : {
11:

>


: , . , - ,
-
.

-
,
-, ,
.

,
, . ,
, , 9.6.

. ,
. :
CAT(const CAT & theCat);

CAT CAT.
- theCat.
, , - -
. ; ,
, , -
.
-
, .
.

272

, CAT - theCat,
,
. theCat CAT
theCat CAT.
(. 10.1).

. 10.1. ,

,
CAT. ,
, .
CAT , CAT
, .
. 10.2.

. 10.2.

,
,
-
. 10.5

10.5. -______________________________________________
1:

// 1 0 .5 .

2:

// -

3:
4:

include <iostream.h>

5:

6:

class CAT

7:
{
8: public:
9:
CAT();

//

10:

// -

CAT (const CAT &);

10.

273

11:

"CATO; //

12:

int GetAgeO const { return *itsAge; }

13:

int GetWeightO const { return *itsWeight; >

14:

void SetAge(int age) { *itsAge = age; }

15:
16:

private:

17:

int *itsAge;

18:

int *itsWeight;

19:

} ;

20:
21:

CAT:: CATO

22:

23:

itsAge = new int;

24:

itsWeight = new int;

25:

itsAge = 5;

26:

*itsWeight = 9;

27:

28:
29:

CAT::CAT(const CAT & rhs)

30:

31:

itsAge = new int;

32:

itsWeight = new int;

33:

*itsAge = rhs.GetAgeO;

34:

itsWeight = *(rhs.itsWeight); //

35:

//

36:
37:

CAT::'CATO

38:

39:

delete itsAge;

40:

itsAge = 0;

41:

delete itsWeight;

42:
43:
44:

itsWeight =0;
}

45:
46:

int mainO
{ ;

47:

CAT frisky; .

48:

cout "frisky's age: " << frisky.GetAge() << endl;

49:

cout << "Setting frisky to 6...\ n";

50:

frisky.SetAge(6);

51:

cout "Creating boots from frisky\ n";

52:

CAT boots(frisky);

53:

cout "friskys age: " << frisky.GetAge() << endl;

54:

cout << "boots age: " boots.GetAgeO << endl;

55:

cout << "setting frisky to 7.. n";

56:

frisky.SetAge(7);

57:

cout << "friskys age: " frisky.GetAgeO endl;

58:

cout << "boot's age: " << boots. GetAgeO << endl;

59:

return 0;

60:' }

274

friskys age: 5
Setting frisky to 6...
Creating boots from frisky
frisky's age: 6
boots' age: 6
setting frisky to 7. . .
friskys age: 7
boots' age: 6

6 19 CAT. , 9 ,
10 -.
17 18 -,
. ,
-
.
-,
.
21 27
.
29. ,
rhs. rhs,
right-hand side ( ), .
33 34, ,
( ).
. 31 32
. , 33 34
CAT.
rhs CAT,
. CAT, rhs CAT.
CAT -
CAT.
, . - rhs.GetAge()
, - itsAge, rhs.
, , . 10.3. ,
- CAT,
, - CAT.
47 frisky CAT. ,
frisky, , 50
6. 52 frisky
boots CAT.
frisky, .
53 54 . ,

frisky boots 6, boots


, 5.
56 7
. frisky
7, boots 6. ,
frisky boots .

10.

275

. 10.3.

CAT,
. CAT
37 43. delete itsAge itsWeigth,
.


C++ , int, real, char
..
(+) (*). , C++
.
, 10.6
Counter. Counter
,
.

10.G. C o u n t e r
1:

// 10.6.

2:

// Counter

3:
4:

int

5:

include <iostream.h>

6:
7:

class Counter

8:

9: public:
10:

Counter();

11:

~Counter(){ }

12:

int GetItsVal()const { return itsVal; }

13:

void SetItsVal(int x) { itsVal = x; )

14:
15: private:
16:

276

int itsVal;

17:
18: } ;
19:
20: Counter::Counter():
21: itsVal(O)
22: { }

23:
24: int main()
25: {
26:

Counter i;

27:

cout << "The value of i is " << i.GetItsVal() << endl;

28: return 0;
29: }

* * i The value of i is 0

*- 1
'

7 18,
. -
int. , 10
20, - .
int, Counter
, ,
.
.


, ,
. ,
Counter.
, , 10.7.

10.7. ________________________________
1:

// 10.7.

2:

// Counter

3:
4:

int

5:

include <iostream.h>

6:
7:

class Counter

8:

<

9: public:
10:

Counter();

11:

~Counter(){ }

12:

int GetItsVal()const { return itsVal; }

13:

void SetItsVal(int x) { itsVal = x; }

14:

void IncrementO { ++itsVal; }

10.

private:
int itsVal;

}
Counter::Counter():
itsVal(O)

{>
int main()

{
Counter i;
cout << "The value of i is " << i.GetltsValQ endl;
i.Increment();
cout "The value of i is " << i.GetItsVal() << endl;
return 0;

The value of is 0

The value of is 1

10.7 , 0 14_ ,
. ++1,
.
...


,
:
returnType Operator op ()

.

void operator++ ()

10.8.

10.8.
// 10.8.

// Counter
int
include <iostream.h>
class Counter

278

9:

public:

10:

CounterO;

11:

'Counter(){ }

12:

int GetItsVal()const { return itsVal; }

13:
14:

void SetItsVal(int x) { itsVal = x; }


void Increments) { ++itsVal; >

15:

void operator++ () <

++itsVal; }

16:
17:

private:

18:

int itsVal;

19:

20: } ;
21 :
22: Counter::Counter( ) :
23: itsVal(O)
24: { }
25:
26: int main()
27: {
28:
29:

Counter i;
cout

"The

value

of

i is

"

i is

"

i.GetltsValO

endl;

<<

endl;

30: i.IncrementO;
31:

cout

<<

"The

value

of

i.GetltsValO

32: ++i;
33:

cout

"The

value

of

i is " << i.GetltsValO << endl;

34: return 0;
35:

The value of i is 0
The value of i is 1
The value of i is 2

15 operator++,
32. Counter ,
.
, ,
,
.

. :
Counter = ++i;

Counter ,
i. ,
Counter. void.
void Counter. ( -
!)

10.

279


, , Counter ,
Counter. ?
, .
10.9.

10.8.
1: // 10.9.
2: //

3:
4: int
5: #include <iostream.h>

6:
7: class Counter

8: {
9: public:
10:

Counter();

11:

Counter(){ }

12:

int GetItsVal()const { return itsVal; }

13:

void SetItsVal(int x) { itsVal = x; }

14:

void IncrementO { ++itsVal; }

15:

Counter operator++ ();

16:
17: private:
18:

int itsVal;

19:

20: } ;

21:
22: Counter::Counter() :
23: itsVal(O)
24: { >
25:
26: Counter Counter::operator++()
27: {
28: ++itsVal;
29: Counter temp;
30: temp.SetltsVal(itsVal);
31: return temp;
32: }
33:
34: int main()
35: {
36: Counter i;
37: cout "The value of i is " << i.GetltsValO endl;
38: i.Increment();
39: cout "The value of i is " << i.GetltsValO << endl;
40:

++i;

41: cout << "The value of i is " i.GetltsValO << endl;

280

42:

Counter = ++i;

43:

cout "The value of a: " << a.GetltsValO;

44:

cout " and i: " i.GetItsVal() endl;

45:

return 0;

46: }

The value of i is 0
The value of i is 1
The value of i is 2
The value of a: 3 and i: 3

operator++ 15
, Counter. 29
temp, Counter.
, 42,
.


,
29. Counter
,
. 10.10.

10.1D.
1: // 10.10.
2: //

3:
4: int
5: include <iostream.h>

6:
7: class Counter

8: {
9: public:
10:

Counter();

11 :

Counter(int val);

12:

'Counter(){ }

13:

int GetItsVal()const { return itsVal; }

14:

void SetItsVal(int x) { itsVal = x; }

15:

void IncrementO { ++itsVal; }

16:

Counter operator++ ();

17:
18: private:
19:

int itsVal;

20:
21: } ;
22:
23: Counter::Counter():

10.

281

24:
25:

itsVal(O)

<>

26:
27:

Counter::Counter(int

28:

itsVal(val)

29:

{>

val):

30:
31 :
32:

Counter Counter::operator++()

33:

++itsVal;

34:

return Counter (itsVal);

35:

>

36:
37:
38:

int main()

<

39:

Counter i;

40:

cout << "The value of i is" << i.GetItsVal() endl;

41 :

i.Increment( ) ;

42:

cout

43:

++i;

44:

cout "The value of i is" << i.GetItsVal() endl;

45:

Counter a = ++i;

46:

cout << "The value of a: " a.GetItsVal();

47:

cout

48:

return 0;

"The

"

value

and

i:

of

"

is"

i.GetltsValO

i.GetltsValO

<<

endl;

endl;

49:

The value of i is 0
The value of i is 1
The value of i is 2
The value of a: 3 and i: 3

11 ,
int. 27 29.
itsVal ,
.

. 33
itsVal. 34
Counter, itsVal.
.
, ,
. ,
.
, i ,
? this.

282

this
this.
- ,
-. this i , itsVal
. 10.11 this,
.

10.11. t h i s __________________________________________
1 : // 1 0 .1 1 .

2: // this

3:
4: int
5: include <iostream. h>

6:
7: class Counter

8: {
9: public:
10:

Counter();

11:

'Counter(){ }

12:

int GetItsVal()const { return itsVal; }

13:

void SetItsVal(int x) { itsVal = x; }

14:

void IncrementQ { ++itsVal; }

15:

const Counter& operator++ ();

16:
17:
18:

private:
int itsVal;

19:

20: } ;
21:
22: Counter::Counter():
23: itsVal(O)
24: { } ;
25:
26: const Counter& Counter::operator++()
27: {
28: ++itsVal;
29: return this;
30: }
31;
32; int main()
33: {
34;

Counter i;

35; cout << "The value of i is " << i.GetItsVal() << endl;
36: i.Increment();
37; cout << "The value of i is " i.GetltsValO << endl;
38: ++i;
39; cout "The value of i is " << i.GetltsValO << endl;

10.

283

40

Counter a = ++i;

41

cout

<<

42

cout

43

return 0;

"The
"

and

value
i:

of

"

<<

a:

"

a.GetltsValO;

i.GetltsValO

endl;

44

The value of is 0
The value of is 1
The value of is 2
The value of a: 3 and : 3

26 30 this . Counter .
, Counter ,
-. , , .
,
Counter, -
. const,
.


.
? :
.
,
. .
, , .


,
, .
4 (. 4.3).
, , ,
, .
,
,
. , ,
,
.
. :
= ++;

5,
5, 6.
, , 5

284

, 6,
.
, , ,
, ,
.
10.12 .

10.12. _____________________________
1: // 10.12.
2: // this

3:
4: int
5: include <iostream.h>

6:
7: class Counter

8: {
9: public:
10: Counter();
11:
"Counter(){ }
12:

int GetItsVal()const { return itsVal; }

13: void SetItsVal(int x) { itsVal = x; >


14:

const Counter& operator++ ();

//

15:

const Counter operator++ (int);

//

16:
17: private:
18: int itsVal;
19: } ;

20:
21: Counter::Counter():
22: itsVal(O)
23: { }
24:
25: const Counters, Counter: :operator++()
26: {
27:

++itsVal;

28: return this;


29: }
30:
31: const Counter Counter::operator++(int x)
32: {
33: Counter temp(*this);
34: ++itsVal;
35:

return temp;

36: }
37:
38: int main()
39: {
40: Counter i;
41: cout << "The value of i is " i.GetltsValO endl;

10.

285

42:

i++;

43:
44:

cout "The value of i is " i.GetltsValO endl;


++i;

45:
46:
47:
48:
49:
50:
51:
52:
53:

cout "The value of i is " i.GetltsValO endl;


Counter a = ++i;
cout "The value of a: " a.GetltsValO;
cout << " and i: " << i.GetltsValO << endl;
a = i++;
cout << "The value of a: " << a.GetltsValO;
cout " and i: " i.GetltsValO endl;
return 0;
>

fgffff The
|,

value of i is 0
The value of i is 1
The value of i is 2
The value of a: 3 and i: 3
The value of a: 3 and i: 4

15
31 36. ,
14 ,
. ,
, .
.


, .
operator, .
,
, .
:
const Counter^ Counter::operator++ ();

:
const Counters Counter::operator-- (int);


, ,
. (+) .
.
Counter?
, Counter,
, :
Counter _, _, _;

_= _ + _;

286

Add(), Counter
. , Counter
. 10.13.

10.13. A d d ( ) _______________________________
1 : // 1 0 .1 3 .

2: // Add

3:
4: int
5: include <iostream.h>

6:
7: class Counter

8: {
9: public:
10: Counter();
11: Counter(int initialValue);
12: Tounter(){ }
13: int GetItsVal()const {return itsVal; }
14:
15:

void SetItsVal(int x) {itsVal = x; >


Counter Add(const Counter &);

16:
17: private:
18:

int itsVal;

19:

20: } ;
21:
22: Counter::Counter(int initialValue):
23: itsVal(initialValue)
24: { }
25:
26: Counter::Counter():
27: itsVal(0)
28: { }
29:
30: Counter Counter::Add(const Counter & rhs)
31: {
32:

return Counter(itsVal+ rbs.GetltsValO);

33: }
34:
35: int main()
36: {
37:

Counter var0ne(2), varTwo(4), varThree;

38: varThree = varOne.Add(varTwo);


39: cout << "varOne: " << varOne.GetItsVal()<< endl;
40: cout << "varTwo: " << varTwo.GetItsVal() endl;
41: cout << "varThree: " varThree.GetItsVal() endl;
42:
43: return 0;
44: }

10.

287

varOne:

varTwo:

varThree: 6

Add () 15.
Counter, , . Counter,
,
(=), 38. varOne , varTwo
Add(), a varThree ,
.
varThree -
, , .
varThree , 2224.
, , 11.


Add() 3033. ,
. (+)
Counter ( 10.14).

10.14. ___________________________________
1:

// 10.14.

2:

// (+)

3:
4:

int

5:

include <iostream.h>

6:
7:

8:

class Counter

9:
10:

public:
Counter();

11:

Counter(int initialValue);

12:

"Counter(){ >

13:

int GetItsVal()const { return itsVal; >

14:

void SetItsVal(int x) { itsVal = x; }

15:

Counter operator+ (const Counter &);

16:

private:

17:

int itsVal;

18:

} ;

19:

20:

Counter::Counter(int initialValue):

21:

itsVal(initialValue)

22:

{}

23:
24:

Counter::Counter():

25:

itsVal(O)

26:

{ }

27:

288

28: Counter Counter::operator+ (const Counter & rhs)


29: {
30: return Counter(itsVal + rhs.GetltsValO);

31: }
32:
33: int main()
34: {
35: Counter var0ne(2), varTwo(4), varThree;
36: varThree = varOne + varTwo;
37: cout << "varOne: " << varOne.GetItsVal()<< endl;
38: cout << "varTwo: " << varTwo.GetItsVal() << endl;
39: cout << "varThree: " << varThree.GetItsVal() << endl;
40:
41: return 0;
42: }

<.,}
t-. x

varOne: 2
varTwo: 4
varThree: 6

15 (operator+),
2831.
Add () . .
.
, (+)
varThree = varOne + varTwo;

Add():
varThree = varOne.Add(varTwo);

,
, .

,
, (operator--).

(operator++),


,
, , .
.
Counter:
'
Counter Counter::operator+ (const Counter & rhs);
:
Counter Counter::operator~ (const Counter & rhs);

10.

289


-,
, -, .
14
.
.
(=), ([]), (())
(->).
[ ] ,
14
.


( int).
.
, ,
. ,
; , (**)
.
, ,
. ,
(, : myValue++), ,
(, : +).
?,
: ( > b ? : ).


,
C++, (
) .
.
,
.
, + ,
* ,
, .
+ ,
/ ,
,
. ,
,
. ,
,
, .

290

,

.

.


,
.


, , ,
, , , ,
(operator=()).
, , :
CAT catOne(5,7);
CAT catTwo(3,4);
// ...
catTwo = catOne

catOne, itsAge
5, itsWeigth 7. catTwo
3 4.
catTwo catOne.
, itsAge ,
catTwo?
-,
, (. . 10.1 10.2).
C++ .
,
.

.
. 10.3.
.
,
. , catTwo ,
.
.
, catTwo :
catTwo = catTwo

,
. ,

, .
,
catTwo,
catTwo , .

10.

291

,
,
. this,
10.15.

10.15.

// 10.15.

// -

3
4

#include <iostream.h>

class CAT

{
public:
CAT();

//

// - !
int GetAgeO const { return *itsAge; }
int GetWeightO const { return *itsWeight; }
void SetAge(int age) { *itsAge = age; >
CAT & operator=(const CAT &);
private:
int *itsAge;
int *itsWeight;

>;
CAT::CAT()

{
itsAge = new int;
itsWeight = new int;
itsAge = 5;
itsWeight = 9;

CAT & CAT::operator=(const CAT & rhs)

{
if (this == &rhs)
return this;
*itsAge = rhs.GetAge();
itsWeight = rhs.GetWeightO;
return *this;

int mainO

{
CAT frisky;
cout << "friskys age: " << frisky.GetAgeO << endl;
cout << "Setting frisky to 6...\ n";

292

45

frisky.SetAge(6);

46

CAT whiskers;

47

cout << "whiskers' age:

48

cout << "copying frisky to whiskers...\ n";

49

whiskers.GetAge() << endl;

whiskers = frisky;

50

cout << "whiskers' age:

51

<< whiskers.GetAge() endl;

return 0;

52

" ,

frisky's age: 5

'

Setting frisky to 6...


whiskers age: 5
copying frisky to whiskers...
whiskers' age: 6

10.15 CAT. ,
' ' -
. 14 ,
3037.
32 , ,
, CAT,
. , rhs this.
, (=)
, , .
*fr


, int unsigned short, , ?
10.16 Counter
int.

10.16 !

10.16. C o u n t e r
i n t ______________________________
1:

// 10.16.

2:

// !

3:
4:

int

5:

include <iostream.h>

6:
7:

class Counter

10.

293

8:

9:

public:

10:

CounterO;

11:

~Counter(){ }

12:int GetItsVal()const { return itsVal; }


13:void SetItsVal(int x)
14:

private:

15:

int itsVal;

{ itsVal = x; }

16:
17:

} ;

18:
19 :

Counter ::Counter():

20:

itsVal(O)

21:

{}

22:
23:

int main()

24:

25:

int theShort = 5;

26:

Counter theCtr = theShort;

27:cout << "theCtr: " << theCtr.GetItsVal() << endl;


28:
return 0;
29:

,
int Counter.
Counter, 7-17,
, .
int Counter,
26. , ,
int - itsVal.
10.17
. , Counter
int.
t'

10.17. i n t C o u n t e r
I : // 10.17.
2: //

3:
4: int
5: include <iostream.h>

6:
7: class Counter

8: <
9:

public:

10:

CounterO;

II :
12;

Counter(int val);
'Counter(){ }

13:

int GetltsValOconst { return itsVal; }

294

14:

void SetItsVal(int x) { itsVal = x; }

15:

private:

16:

int itsVal;

17:
18: } ;
19:
20:

Counter::Counter():

21:

itsVal(O)

22: { }

23:
24: Counter::Counter(int val):
25: itsVal(val)
26: { }
27:
28:
29: int main()
30: {
31: int theShort = 5;
32:

Counter theCtr = theShort;

33:
34:

cout << "theCtr: " << theCtr. GetltsValQ << endl;


return 0;

35: }

the Ctr; 5

11,
, int,
2426, .
- Counter int.
,
.
.

1: Counter theCtr.
, ; int = 5,
5. theCtr
Counter, theShort short int.
2: theCtr theShort.
short, Counter! , ,
Counter.
, , .
Counter,
, short:
class Counter

{
Counter (short int x);

// . . .
};

10.

295

Counter,
, short.
, , short
, Counter wasShort.

3: wasShort thoCtr,
"theCtr = wasShort";

wasShort, ,
theCtr, Counter.
, theCtr.
, ,
, ,
operator. ( =
+) ,
. ,
= b


a.operator=(b);

, , :
1 : Counter theCt(5);
2: int theShort = theCtr;
3: cout << "theShort : " << theShort endl;

.
, Counter int,
, .


, C++
, .

.
10.18. :
. ,
.

10.18. C o u n t e r
1:

u n s i g n e d

short( )

include ciostream.h>

2:
3:

class Counter

4:

5:

public:

6:

Counter();

7:

Counter(int val);

8:

'Counter(){ }

9:

int GetItsVal()const { return itsVal; }

10:

296

void SetItsVal(int x) { itsVal = x; }

11: operator unsigned short();


12: private:
13: int itsVal;
14:
15: } ;
16:
17: Counter::Counter():
18: itsVal(O)
19: < }

20:
21: Counter::Counter(int val):
22: itsVal(val)
23: < }
24:
25: Counter::operator unsigned short ()
26: {
27: return ( int (itsVal) );
28: }
29:
30: int main()
31: <
32: Counter ctr(5);
33: int theShort = ctr;
34: cout "theShort: " theShort << endl;
35: return 0;
36: }

theShort: 5

11 . * ' , .
2528. 27 itsVal,
int.
, int
,
int.
'''

- .
, , ,
.

, .
,
.

10.

297

-
, .
, ,
. ,
,
,
.
C++ ,
,
. ,
, , C++.
this
-. this
.

, .
, ,
, , , .
.


, , ?
, . ,
, , ,
, . ,

.

, ?
,
, , . ,
, .

-
, ?
:
-. ,

.

, ?
. ,
.
, .
,
.

- , ?
,
inline. ,

298

, . ,
-
inline, .


,
.
, .
,
.


1.

-,
?

2.

3. -?
4.

5. - (=)?
6. this?
7.

8. operator^ short int?

9.

C++ operator++ ,
?

10.

1.

SimpleCircle

itsRadius. ,

, .
2.

, 1, ,
, itsRadius 5.

3.

,
itsRadius.

4.


SimpleCircle itsRadius.

5.

SimpleCircle , itsRadius
.

6. SimpleCircle -.
7. SimpleCircle .

10.

299

8.

, SimpleCircle.
, ,
9.
. ,
.

9.

:
?
SQUARE SQUARE ::operator=(const SQARE & rhs)

<
itsSide = new int;
itsSide = rgs.GetSideO;
return *this;

}
10. :
?
VeryShort VeryShort ::operator+ (const VeryShort& rhs)

{
itsval += rhs. GetltsValO;
return *this;

>

300


,
.
,
, , .
, ++
. :


? , ?
, .
, ,
, ,
/.
,
, :
, ..

: , , , , , .

. , .
. , , ,
. ,
.
, -,
. , ,
, ( )
.

11.

301


, , ,
, .
, , ,
. .
,
, , ,
, ... , ! , .
, , .
: , ..
, , ,
, , ,
, .., ,
. . 11.1,
.

. 11.1.
C++ ,
.
. ,
Dog () Mammal (). ,
Mammal Dog. ,
, ,
Dog , ,
Mammal.

302

, .
, ,
C++ , Mammal.


,
.
, , .
, , ,
, , , ..,
, ,
. .
,
, .
, ,
, , .


class,
, , (public
- ), , :
class Dog : public Mammal

.
. ,
, ,
. Dog Mammal 11.1.

11.1. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1:

/ / 1 1 . 1 .

2:

3:

include <iostream.h>

4:enum BREED { GOLDEN, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB }


5:
6:

class Mammal

7:

8:

public:

9:

//

10:

Mammal();

11:

"MammalO;

12:

13:

//

14:

int GetAge()const;

15:

void SetAge(int);

16:

int GetWeightO const;

17:

void SetWeightO;

18:
19:

//

11.

303

20

void Speak() const;

21

void Sleep() const;

22
23
24

protected:

25

int itsAge;

26
27

int itsWeight;
} ;

28
29

class Dog : public Mammal

30

<
public:

31
32
33

//

34

Dog();

35

'Dog();

36
37

//

38

BREED GetBreed() const;


void SetBreed(BREED);

39
40
41

//

42

WagTail();

43

BegForFoodO;

44
45

protected:

46
47

BREED itsBreed;
> ;

,
.
.
Mammal 627. ,
,
, . C++
, .
, ,
. ,
,
.
,
Mammal.
-, ,
. ,
. Mammal
Animals, , .
.
Mammal

304


, Mammal : ,
SpeakQ Sleep().
29 Dog Mammal. Dog
-: itsAge, itsWeight itsBreed. ,
Dog itsAge itsWeight. Dog
Mammal ,
Mammal, , .


, , 24 45 11.1
protected.
private. , private, .
, - itsAge
itsWeight public, ,
.
: -
, .
, protected.
,
.
: public, protected private.
,
- -, public.
- , ,
( private) ,
( protected).
, Dog: :WagTail()
itsBreed Mammal, public
protected.
Dog Mammal ,
- (, DomesticAnimals),
Dog Mammal,
, Dog public.
private 15.
11.2 Dog
.

1 1 . Z . _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1:

// 11,2.

2:
3:

include <iostream.h>

4:

enum BREED < GOLDEN, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB } ;

5:
6:

class Mammal

7:

11.

305

8:

public:

9:

//

10:

Mammal():itsAge(2), itsWeight(5){ }

11:

'Mammal(){ }

12:
13:

//

14:
15:

int GetAge()const { return itsAge; >


void SetAge(int age) { itsAge = age; }

16:
17:

int GetWeightO const { return itsWeight; }


void SetWeight(int weight) { itsWeight = weight; }

18:
19:

//

20:

void Speak()const { cout "Mammal sound!\ n"; }

21:

void Sleep()const { cout << "shhh. Im sleeping.\ n"; }

22:
23:
24:

protected:

25:
26:
27:

int itsAge;
int itsWeight;
} ;

28:
29:

class Dog : public Mammal

30:

31:
32:

public:

33:
34:

//
Dog():itsBreed(GOLDEN){ }

35:

~Dog(){ }

36:
37:

//

38;
39:

BREED GetBreedO const { return itsBreed; }


void SetBreed(BREED breed) { itsBreed = breed; }

40:
41:

//

42:
void WagTailO const { cout << "Tail wagging...\ n"; }
43: void BegForFood() const { cout << "Begging for food...\
44:
45:

private:

46:
47:

BREED itsBreed;
} ;

n";

48:
49:

int main()

50:

51:
52:

Dog fido;
fido.Speak();

53;

fido.WagTailO;

54:
55:

cout << "Fido is " << fido.GetAgeO << " years old\ n";
return 0;

56:

306

Mammal sound!
Tail wagging...
Fido is 2 years old

6-27 Mammal (
). 29~47 Mammal
Dog. Fido
WagTailO, Speak() Sleep().

*'5


Dog Mammal.
. Dog Fido,
Mammal , .
Dog, .
Fido ,
, . Fido ,

Mammal Dog.
Fido
Dog, Mammal.
,
. , ,
11.3.

11.3. ___________________________________
1:

// 11.3. .

2:
3:

include <iostream.h>

4:
5:

enum BREED { GOLDEN, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB } ;

6:

class Mammal

7:
8:

{
public:

9: //
10: MammalO;
11:

"MammalO;

12:

13:

//

14:

int GetAge() const { return itsAge; }

15:

void SetAge(int age) { itsAge = age; >

16:

int GetWeightO const { return itsWeight; }

17:
18:

void SetWeight(int weight) { itsWeight = weight; }

19:

//

20:

void SpeakO const < cout << "Mammal sound!\ n"; }

21:

void SleepO const { cout "shhh. Im sleeping.\ n; >

22:

11.

307

23:
24: protected:
25: int itsAge;
26: int itsWeight;

27: } ;
28:
29: class Dog : public Mammal
30: {
31: public:
32:
33: //
34: Dog();
35: -Dog();
36:
37: //
38: BREED GetBreed() const { return itsBreed; >
39: void SetBreed(BREED breed) { itsBreed = breed; }
40:
41:
42:
43:
44:
45:
46:

//
void WagTailO const { cout "Tail wagging...\ n"; }
void BegForFood() const { cout << "Begging for food...\ n"; >
private:
BREED itsBreed;

47: > ;
48:
49: Mammal::Mammal():
50; itsAge(1),
51; itsWeight(5)
52: {
53: cout << "Mammal constructor...\ n";
54: }

55:
56: Mammal::'Mammal()

57: {
58: cout << "Mammal destructor..,\ n";
59: }

60:
61: Dog::Dog():
62; itsBreed(GOLDEN)
63: {
64: cout "Dog constructor...\ n";
65: }
66:
67: Dog::'Dog()
68; {
69: cout << "Dog destructor..,\ n";

70: }
71: int main()
72: {

308

73:

Dog fido;

74:

fido.Speak();

75:

fido.WagTail();

76:
77:

cout "Fido is " fido.GetAge() " years old\ n":


return 0;

78:

Mammal constructor...
Dog constructor...
Mammal sound!
Tail wagging...
Fido is 1 years old
Dog destructor...
Mammal destructor...

11.3 11.2 ,

. Mammal, Dog.
Dog .
Fido,
, Dog, Mammal.


, ,
Mammal Dog, ,
, .
Mammal ? ,
Mammal, Dog?
, ,
, , 11.4.

1 1 . 4 . _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1:

// 11.4.

2:

3:

include ciostream.h>

4:
5:

enum BREED { GOLDEN, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB } ;

6:

class Mammal

7:
8:

{
public:

9: //
10: Mammal();
11: Mammal(int age);
12: 'MammalO;
13:
14: //
15: int GetAge() const { return itsAge; }

11.

309

16:

void SetAge(int age) { itsAge = age; }

17:

int GetWeightQ const { return itsWeight; }

18:

void SetWeight(int weight) { itsWeight = weight; }

19:
20:
//
21:
void Speak() const { cout << "Mammal sound!\ n"; >
22: void SleepO const { cout << "shhh. I'm sleeping,\ n"; }
23:
24:
25:

protected:

26:

int itsAge;

27:

int itsWeight;

28:
29:

} ;

30:

class Dog : public Mammal

31:
32:

{
public:

33:
34:
35:
36:
37:
38:

//
Dog();
Dog(int age);
Dog(int age, int weight);
Dog(int age, BREED breed);

39:

Dog(int age, int weight, BREED breed);

40:

'Dog();

41:
42:
43:
44:

//
BREED GetBreedO const { return itsBreed; }
void SetBreed(BREED breed) { itsBreed = breed; }

45:
46:

//

47: void WagTail() const { cout "Tail wagging...\ n"; )


48: void BegForFoodQ const { cout << "Begging for food...\
49:
50:
51:

private:
BREED itsBreed;

52:

} ;

53:
54:

Mammal::Mammal():

55:
56:
57:

itsAge(1),
itsWeight(5)
{

58:

cout << "Mammal constructor..,\ n";

59:

>

60:
61:

Mammal:'.Mammal(int age):

62:

itsAge(age),

63:
64:
65:

itsWeight(5)
{
cout << "Mammal(int) constructor...\ n";

310

n";

66 :

>

67:
68: Mammal::"Mammal()
69: {
70: cout "Mammal destructor...\ n";
71:
72:
73:
74:
75:

}
Dog::Dog():
MammalO,
itsBreed(GOLDEN)

76: {
77: cout << "Dog constructor...\ n";
78: }
79:
80: Dog::Dog(int age):
81: Mammal(age),
82: itsBreed(GOLDEN)
83: {
84: cout << "Dog(int) constructor...\ n";
85: }
86 :
87: Dog::Dog(int age, int weight):
88: Mammal(age),
89: itsBreed(GOLDEN)
90: {
91: itsWeight = weight;
92: cout << "Dog(int, int) constructor...\ n";
93: }
94:
95: Dog::Dog(int age, int weight, BREED breed):
96: Mammal(age),
97: itsBreed(breed)
98: {
99: itsWeight = weight;
100: cout "Dog(int,

int,

BREED)

constructor...\

n";

101: }
102:

103: Dog::Dog(int age, BREED breed):


104: Mammal(age),
105: itsBreed(breed)
106:
107

cout << "Dog(int, BREED) constructor...\ n";

108:
109:
110: Dog::'Dog()

111:
cout "Dog destructor..,\ n";
113:
114: int main()
115:

112:

11.

311

116:
117:

Dog fido;
Dog rover(5);

118:

Dog buster(6,8);

119:
120:
121:

Dog yorkie (3,GOLDEN);


Dog dobbie (4,20,DOBERMAN);
fido.Speak():

122:

rover.WagTail();

123:
124:
125:

cout "Yorkie is " yorkie.GetAge() << " years old\ n"


cout "Dobbie weighs
cout << dobbie.GetWeightO << " pounds\ n";

126:
127:

return 0;
}

Mammal constructor...

Dog constructor...

3 Mammal(int) constructor. . .
4

Dog(int) constructor...

Mammal(int) constructor...

Dog(int, int) constructor...

Mammal(int) constructor...

Dog(int, BREED) constructor....

Mammal(int) constructor...

10 Dog(int, int, BREED) constructor...


11

Mammal sound!

12

Tail wagging...

13

Yorkie is 3 years old.

14

Dobbie weighs 20 pounds.

15

Dog destructor..,

16

Mammal destructor...

17

Dog destructor...

18

Mammal destructor...

19

Dog destructor...

20

Mammal destructor...

21

Dog destructor...

22

Mammal destructor...

23

Dog destructor, . .

24

Mammal destructor...

'* 11.4 Mammal 11


, .
6166 itsAge 5,
.
Dog 3539 .
, . -

312

, Mammal.
, , , .
, 74 Dog
Mammal. ,

, . ,
.
8085 Dog,
. ( 81 82)
, .
Dog 8793.
.
,
itsWeight Dog. ,

. Mammal
, ,
Dog.
,
. ,
,
.
.
Fido
, .
3 4 rover, 5 6
buster. , Dog
Mammal,
.

.
Dog, Mammal.


Dog - Mammal,
-, Dog,
WagTaill(). ,
.
, .

, , .

. ,
, , ,
, const.
11.5 Dog SpeakO,
Mammal.
.

11.

313

U . S .
1: // 11.5.
2:

3: include <iostream.h>
4: enum BREED { GOLDEN, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB } ;
5:
6: class Mammal
7: {
8: public:
9: //
10: Mammal() < cout << "Mammal constructor...\ n"; }
11: "Mammal() { cout << "Mammal destructor..,\ n"; }

12:
13: //
14: void Speak()const { cout << "Mammal sound!\ n"; }
15: void Sleep()const { cout << "shhh. I'm sleeping.\ n"; }
16:
17:
18: protected:
19:

int itsAge;

20: int itsWeight;


21: } ;
22:
23: class Dog : public Mammal
24: <
25: public:
26:
27:

//

28: Dog(){ cout "Dog constructor...\ n"; }


29: Dog(){ cout "Dog destructor...\ n"; >
30:
31:

//

32: void WagTailO const { cout "Tail wagging...\ n"; }


33: void BegForFood() const { cout << "Begging for food...\ n"; }
34: void Speak() const { cout << "Woof!\ n"; }
35:
36: private:
37:

BREED itsBreed;

38: > :
39:
40: int main()
41: {
42:

Mammal bigAnimal;

43:

Dog fido;

44:

bigAnimal.Speak();

45:

fido.Speak();

46: return 0;
47: }

314

Mammal constructor...
Mammal constructor...
Dog constructor...
Mammal sound!
Woof!
Dog destructor...
Mammal destructor...
Mammal destructor...

34 Dog

Dog Woof!. 42 bigAnimal Mammal,
Mammal
. 43 Fido Dog,
Mammal,
Dog. .
44 Mammal Speak(), 45
Dog .
, SpeakQ Dog .

.
Speak(),

.
,
.
, , .


SpeakQ Dog
, SpeakQ
. , , . Mammal
Move(), Dog, ,
MoveQ Dog .
.
. , Mammal Move
. ,
(),
( ). Dog MoveQ .
Dog
Mammal .
11.6.

11.

315

1 1 . 6 .
1: // 11.6.
2:

3: include <iostream.h>
4:
5: class Mammal

6: <
7: public:
8: void Move() const { cout "Mammal move one step\ n"; }
9: void Move(int distance) const
10:{

11: cout "Mammal move


12: cout distance " steps.\ n";
13: }
14: protected:
15: int itsAge;
16:

int itsWeight;

17: } ;
18:
19: class Dog : public Mammal
20: {
21: public:
22: // , , !
23: void Move() const { cout << "Dog move 5 steps.\

n"; }

24: } ;
25:
26: int main()
27: {
28: Mammal bigAnimal;
29: Dog fido;
30:

bigAnimal.Move();

31:

bigAnimal.Move(2);

32:

fido.MoveO;

33: // fido.Move(IO);
34: return 0;
35: }

Mammal move one step


Mammal move 2 steps.
Dog move 5 steps.


, . 8 9
Mammal Move(). 23 Move()
Dog.
30 32, , , ,
.

316

33 , .
, Dog
Move(int), Move(),
, Move(int), Dog.

.
, .
,
- ,
const,
. , const ,
, .

. .


, ,
, .
,
. : Mammal: :Move().
11.6 32 , ,
:
32:

fido.Mammal::Move();

, 11.7,
.

11.7. ____________________ _________


1: // 11.7.

2:
3: include <iostream.h>
4:
5: class Mammal
6: {
7: public:
8: void Move() const { cout "Mammal move one step\ n"; }
9: void Move(int distance) const
10: {

11:

cout "Mammal move " << distance;

12:

cout << " steps.\ n";

13: }
14:
15: protected:

11.

317

16: int itsAge;


17: int itsWeight;
18: } ;
19:
20: class Dog : public Mammal

21: {
22: public:
23: void Move()const;
24:
25: } :
26:
27: void Dog::Move() const
28: {
29: cout << "In dog move...\ n";
30: Mammal::Move(3);
31: >
32:
33: int main()
34: {
35:

Mammal bigAnimal;

36: Dog fido;


37:

bigAnimal.Move(2);

38:

fido.Mammal::Move(6);

39: return 0:
40: }

I>"

Mammal move 2 steps.


Mammal move 6 steps.

35 bigAnimal Mammal, 36
fido Dog. 37 Move(int)
Dog.
- ,
Dog Move(),
. Move (int)
38.


- .

318


, Dog
Mammal. ,
Dog () () .
C++
.
C++ ,
, :
Mammal* pMammal = new Dog;


, Mammal.
, .

Dog

. ,
, , ,

)\/().
,
1() ,
. ,
.

Mammal.
, , Dog,
,
. . 11.8 ,
.

11.8. _________________________________
1:

// 11.8.

2:

3:

include <iostream.h>

4:
5:

class Mammal

6:

7:

public:

8:

Mammal():itsAge(1) { cout << "Mammal constructor... \ n"; }

9:

virtual 'MammalO { cout << "Mammal destructor. .. \ n; }

10:

void MoveQ const { cout << "Mammal move one step\ n"; }

11:

virtual void SpeakQ const { cout "Mammal speak! \ n; }

12:

protected:

13:

int itsAge;

14:
15: } ;
16:

11.

319

17: class Dog : public Mammal


18: {
19: public:
20: Dog() { cout "Dog Constructor..,\ n"; }
21: virtual ~Dog()

{ cout << "Dog destructor..,\ n"; }


n"; >

22: void WagTailQ { cout << "Wagging Tail...\


23: void Speak()const { cout << "Woof!\ n; }

24: void Move()const { cout << "Dog moves 5 steps...\ n"; }


25: } ;
26:
27: int main()
28: {
29:
30: Mammal *pDog = new Dog;
31:

pDog->Move();

32:

pDog->Speak();

33:
34: return 0;
35: >

Mammal constructor...
Dog Constructor...
Mammal move one step
Woof!

11 Speak() Mammal.
, .
, .
30 Mammal (pDog),
Dog. ,
. Move().
pDog Mammal,
, Move() Mammal.
32 pDog Speak().
Speak() ,
Speak(), Dog.
- . , pDog
Mammal, ,
. ,
, ,
,
. 11.9.

11.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: // 11.9.
2:

3: include <iostream.h>
4:

320

5: class Mammal
6: {
7: public:
8: MammalO :itsAge(1) { }
9: virtual "MammalO { >
10: virtual void Speak() const { cout "Mammal speak!\ n"; }
11: protected:
12: int itsAge;
13: } ;
14:
15: class Dog : public Mammal
16: {
17: public:
18: void SpeakOconst { cout "WoofI\ n"; }
19: } ;

20:
21:

22: class Cat : public Mammal


23: {
24: public:
25: void SpeakOconst ( cout "Meow!\ n"; }
26: } ;
27:
28:
29: class Horse : public Mammal
30: {
31: public:
32: void SpeakOconst { cout "Whinny!\ n"; }
33: } ;
34:
35: class Pig : public Mammal
36: {
37: public:
38: void SpeakOconst < cout "Oink!\ n"; >
39: } ;
40:
41: int main()
42: {
43: Mammal* theArray[5];
44: Mammal* ptr;
45: int choice, i;
46: for ( i = 0; i<5; i++)
47: {
48: cout << "(1)dog (2)cat (3)horse (4)pig:
49: cin >> choice;
50: switch (choice)
51: {
52:

case 1: ptr = new Dog;

53:

break;

54:

case 2: ptr = new Cat;

11.

321

55

break;

56

case 3: ptr = new Horse;

57

break;

58

case 4; ptr = new Pig;

59

break;

60

default: ptr = new Mammal

61

break;

62

}
theArray[i] = ptr;

63
64

65

for (i=0;i<5;i++)
theArray[i]->Speak();

66
67
68

return 0;
}

(1)dog

(2)cat

(3)horse

(4)pig:

(1)dog

(2)cat

(3)horse

(4)pig:

1
2

(1)dog

(2)cat

(3)horse

(4)pig:

(1)dog

(2)cat

(3)horse

(4)pig:

(1)dog

(2)cat

(3)horse

(4>pig:

Woof!
Meow!
Whinny!
Oink!
Mammal speak!

,
.
Dog, Cat, Horse Pig,
Mammal.
10 SpeakQ Mammal. 18, 25,
32 38 .

, 4664 Mammal
.

. , ,
.
( )

virtual.

322

, .


, Dog,
, .
Dog . 11.2. ,
,
, .
VPTR

Mammal

Mammal

1
V

f Dog

Mammal

Dog

. 11.2. Dog

. 11.3.
Mammal

- ,
.
, -.
,
(1:, -).

, ,
.

. 11.4.
Dog

, vptr,
, , ,
. ( 14.)

11.

323

vptr Dog ,
Mammal, . 11.3.
Dog vptr ,
( ),
Dog (. 11.4).
Mammal vptr ,
. Speak()
, .

,
Dog WagTai 1 (),
Mammal, ,
Mammal (
Dog). WagTaiK)
Mammal, Dog
.
, C++
.
Mammal Dog,
WagTaiK). ,
,
, , 20.


,
.
, .
11.10.

1 1 . 1 0 . _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: // 11.10.
2:

3:

include <iostream.h>

4:

5:

class Mammal

6:
7:

public:

8:

Mammal(): itsAge( 1) { }

9:
virtual 'MammaK) { }
10:virtual void Speak() const { cout << "Mammal speak! \ n"; }
11:

protected:

12:

int itsAge;

13:
14:

} ;

15:

class Dog : public Mammal

16:

324

17:

public:

18:void Speak()const { cout "Woof!\ n"; }


19:

} ;

20:
21:

class Cat : public Mammal

22:

23:

public:

24:void Speak()const { cout "Meow!\ n"; >


25:

} ;

26:
27

void ValueFunction (Mammal);

28:

void PtrFunction (Mammal*);

29:

void RefFunction (Mammal&);

30;

int main()

31:

32:

Mammal* ptr=0;

33:

int choice;

34:

while (1)

35:
36:

{
bool fQuit = false;

37:-cout << "(1)dog (2)cat (O)Quit: ";


38:

cin >> choice;

39:

switch (choice)

40:

41:

case 0: fQuit = true;

42:

break;

43:

case 1: ptr = new Dog;

44:

break;

45:

case 2: ptr = new Cat;

46:

break;

47:

default: ptr = new Mammal;

48:

break;

49:

50:
51:
52:

if (fQuit)
break;
PtrFunction(ptr);

53:

RefFunction(*ptr);

54:

ValueFunct'ion( *ptr);

55:

56:

return 0;

57:

>

58:
59:void ValueFunction (Mammal MammalValue)
60:
61:

{
MammalValue.Speak();

62:
}
63:
64:void PtrFunction (Mammal * pMammal)
65:

66:

pMammal->Speak();

11.

325

67:

68:
69:

void RefFunction (Mammal & rMammal)

70:

71: rMammal.Speak();
72:

(1)dog (2)cat (O)Quit: 1


Woof
Woof
Mammal Speak!
(1)dog (2)cat (O)Quit: 2
Meow!
Meow!
Mammal Speak!
(1)dog (2)cat (O)Quit: 0

525 Mammal, Dog Cat.


PtrFunction(), RefFunction() ValueFunction().
Mammal, Mammal
Mammal. SpeakQ.
Dog Cat,
4346 .
, ,
Dog, 43-
. Dog
, .
,
, - Dog->Speak().
, .
.
Mammal,
Dog ,
Mammal. Speak(),
Mammal, ,
.
Cat.


, ,

. ,
? ,
.
,
.
: ,
.

326

-
, ,
-. ,

. ,
1(). Clone()
.
Clone() ,
, . ,
, 11.11.

11.11. -
1:

// 11.11. -

2:

3:
4:

((include <iostream.h>

5:

class Mammal

6:

7:

public:

8:

Mammal():itsAge(1) { cout << "Mammal constructor...\ n"

9:

virtual ~Mammal() { cout << "Mammal destructor...\ n;

10:

Mammal (const Mammal & rhs);

11:

virtual void Speak() const { cout << "Mammal speak!\ n"

12:

virtual Mammal* Clone() { return new Mammal(*this); }

13:

int GetAge()const { return itsAge; }

14:

protected:

15:

int itsAge:

16:

> ;

17:
18:

Mammal::Mammal (const Mammal & rhs):itsAge(rhs.GetAge())

19:

<

20:
21:

cout << "Mammal Copy Constructor...\ n";


}

22:

23:
24:

class Dog : public Mammal


{

25:

public:

26:

Dog() { cout << "Dog constructor..,\ n"; }

27:
28:

virtual ~Dog() { cout << "Dog destructor...\ n"; }


Dog (const Dog & rhs):

29:

void Speak()const { cout << "Woof!\ n"; }

30:

virtual Mammal* Clone() { return new Dog(*this); }

31:
32:

} :

33:
34:

Dog::Dog(const Dog & rhs):


Mammal(rhs)

35:

36:

cout << "Dog copy constructor...\ n";

11.

327

37:

>

38:
39:

class Cat : public Mammal

40:

41:
public:
42: Cat() { cout << "Cat constructor,,,\ n"; }
43: "Cat() { cout << "Cat destructor...\ n"; >
44:

Cat (const Cat &);

45:

void Speak()const { cout << "Meow!\ n"; }

46:virtual Mammal* CloneO ( return new Cat(*this); }


47:

} ;

48:
49:

Cat::Cat(const Cat & rhs):

50:

Mammal(rhs)

51:
52:

{
cout "Cat copy constructor..,\ n";

53:

54:
55:
56:

enum ANIMALS { MAMMAL, DOG, CAT) ;


const int NumAnimalTypes = 3;

57:

int main()

58:

59:

Mammal *theArray[NumAnimalTypes];

60:

Mammal* ptr;

61:

int choice, i;

62:

for ( i = 0; KNumAnimalTypes; i++)

63:

64:

cout << "(1)dog (2)cat (3)Mammal: ";

65:

cin >> choice;

66:

switch (choice)

67:

68:

case DOG: ptr = new Dog;

69:
70:

break;
case CAT: ptr = new Cat;

71:

break;

72;

default: ptr = new Mammal;

73:
74:

break;
}

75:

theArray[i] = ptr;

76:

>

77:

Mammal *OtherArray[NumAnimalTypes];

78:

for (i=0;i<NumAnimalTypes;i++)

79:

80;

theArray[i]->Speak();

81:

OtherArray[i] = theArray[i]->Clone();

82: }
83: for (i=0; KNumAnimalTypes; i++)
84:

OtherArray[i]->Speak();

85: return 0;

86: }

328

(1)dog

(2)cat

(3)Mammal:

2 Mammal constructor...
3 Dog constructor...
4

(1)dog

Mammal constructor...

(2)cat

(3)Mammal:

6 Cat constructor...
7
8

(1)dog (2)cat (3)Mammal:


Mammal constructor...

9 Woof!
10 Mammal Copy Constructor.
11

Dog

12

Meow!

copy

constructor...

13

Mammal

14

Cat

15

Mammal speak!

16

Mammal

17

Woof!

Copy

copy

Constructor.

constructor.,.

Copy

18

Meow!

19

Mammal speak!

Constructor.

11.11 , Mammal
1(). Mammal,
-, this.
1() Dog Cat
, . 1()
, -,
81.
Dog, Cat Mammal.
62-74. 75
.
,
Speak() 1() (. 80 81).
, 81 .
1 1
Dog.
. Cat Mammal
4-8.
9 SpeakO Dog.
Speak() ,
, .
Clone(),
, Dog Mammal
- Dog.
Cat ( 12-14)
Mammal ( 15 16). ,
Speak().

11.

329


-,

.
, ,
.
, V ( ),
. ,
, , .

,
.

,

.

, .
public
.
.
,
.
.
.
,
.
, ,
. ,
,
, .
,
.
, Dog Mammal,
: Mammal: :walk().
,
. ,
, ,
. .
-
, -.

330


-
? , Dog Mammal, Mammal
Animals, Dog Animals?
. ,
.
Mammal ,
Animals, Dog?
Dog Mammal, ,
Mammal, .. .
private ,
public?
. ,
. , .
?
v-,
.
.
, ,
. .
.
,
, ,
.
. , ,
, ?

.
, , .


,
.
, .
,
.

1. v-?

2. ?
3. ?

11.

331

4.

-?

5.

,
?

6.

,
?

7. ,
,
?
8.

protected?

1. ,
void.
2. Square, Rectangle, ,
, Shape.
3. , Shape
, Rectangle (length width),
Square (length); Square.
4. - Square,
3.
5. : ?
void SomeFunction(Sbape);
Shape * pRect = new Rectangle;
SoneFunction(*pRect) ;

6. : ?
class ShapeO

<
public:
Shape();
Virtual -ShapeO;
Virtual Shape(const Shape&);

};

332


, ,
int, char .
, 20 int CAT. :


,
. .
, , .
, , ,
, :
long LongArray[25];

LongAr ray,
25 long int. ,
, 25 .
long int ,
100 (. 12.1).



, .
. , -

12.

333

: [0]. ,
, : 1[0],
[ 1 ] .. , [],
, { ] [ - 1 ] .

100

. 12.1.
, LongArray[25]
1_[0] LongArray[24]. 12.1
.

12.1. _________________________________
1:

// 12.1.

2:

include <iostream.h>

3:
4:

int nain()

5:

6:

int myAr[5];

7:

int i;

8:

for ( i=0; i<5; i++) // 0-4

9:

10:cout << "Value for myArray[" << i << "]:


11 :

ein >> myArray[i];

12:

13:

for (i = 0; i<5; i++)

14:cout << i << ": " << myArray[i] << "\ n";
15:

return 0;

16:

Value

for myArray[0]

Value

for myArray[1]

Value

for myArray[2]

Value

for myArray[3]

12

Value

for myArray[4]

15

0: 3

1: 6
2: 9
3: 12
4: 15

334

6 ,
. 8 0 4,
.
,
,
.
,
, [0], [1] ..
.

, 0,
1. ++.
, 10 ,
[0]
[9]. [ 10] .


,
.
,
1_, 1.[5].
5 ( 4 )
20 . ,
20 .
1_[50],
,
. , ,
200 ,
. ,
,
. , .
,
. ,
, , , ,
.
, ,
. [0]
, . ,
- :
, .
, . , 20
. [ 100],
25 , ,
. ,
, ,
.
12.2.

12.

335


. .

12.2.
// 12.2.

// ,
//
include ciostream.h>.
int main()

{
//
long sentinel0ne[3];
long TargetArray[25]; //
long sentinelTwo[3];
int i;
for (i=0; i<3; i++)
sentinelOne[i] = sentinelTwo[i] = 0;
for (i=0; i<25; i++)
TargetArray[i] = 0;
cout << "Test 1: \ n"; // test current values (should be 0)
cout << "TargetArray[0]: " << TargetArray[0] << "\ n";
cout << "TargetArray[24]: " << TargetArray[24] << "\ n\ n";
for (i = 0; i<3; i++)

{
cout << "sentinelOne[" << i << "]:
cout << sentinelOne[i] "\ n";
cout << "sentinelTwo[" << i << "]:
cout << sentinelTwo[i]<< "\ n";

>
cout << "\ nAssigning,,,
for (i = 0; i<=25; i++)
TargetArray[i] = 20;
cout "\ nTest 2: \ n";
cout "TargetArray[0]: " TargetArray[0] "\ n";
cout "TargetArray[24]: " TargetArray[24] "\ n";
cout "TargetArray[25]; " TargetArray[25] "\ n\ n";
for (i = 0; i<3; i++)

{
cout

"sentinel0ne["

oout

Sintinel0ne[i]

i
"\

"];

n";

eout "sentinelTwo[" i "]:

336

44: cout << sentinelTwo[i]<< "\ n";


45: >
46:
47: return 0;
48: }

Test 1:
TargetArray[0]:

TargetArray[24]: 0
Sentinel0ne[0]:

SentinelTwo[0]:

SentinelOne[1

]:

SentinelTwo[1

]:

Sentinel0ne[2]: 0
SentinelTwo[2]:

Assigning...
Test 2:
TargetArray[0]: 20
TargetArray[24]: 20
TargetArray[25]: 20
Sentinel0ne[0]:

20

SentinelTwo[0]:

Sentinel0ne[1 ]: 0
SentinelTwo[1 ]: 0
Sent inelOne[2]: 0
SentinelTwo[2]: 0

*' 9 11 long , TargetArray.


0.
TargetArray , , . ,
. ,
TargetArray.
19-29 -
(Test 1). 33 TargetArray 20,
25, TargetArray.
36-38 TargetArray (Test 2).
, TargetAr[25]
20.
- SentinelOne SentinelTwo, ,
Sent InelOne . ,
TargetAr ray [25] ,
SentinelQns[Q]. ,
TargetArray, .

12,

337


- ,
. .
3 25
. , ,
.
, , -
,
.


,
.

, , 10- ,
1 . .
, .
, . 12.2.

. , ,
, 25 , 24
0, 1. (
, 4, .)
-------

[0] ,
. . [0]
, [1]7
? ... [24]
?
[0] , .


(, int char)
.
(=)
, . :
int IntegerArray[5] = {10, 20, 30, 40, 50};

IntegerArray
10, IntegerArray[ 1 ] 20 ..
,
.
;
IntegerArray[0]

int IntegerAr[] = {10. 20, 30, 40, 50};

338

. 12.2.

, .
, ,
:
const USHORT IntegorArrayLength;
Inleget Ar ray Length = sizeof(IntegerArray)/sizeof(IntegerArray[OJ);


.
IntegerArrayLength const USHORT, .
,
, ,
, , :
int IntegerArray[5] = {10, 20, 30, 40, 50, 60);

:
inl IntegerArrayf5] = {10, 20};

,
, . ,
.
, - , ,
, .


, .
,
.


,
. ,
1[5], .
,
, 12,3.

1 2 . 3 .
// 12,3.

//
inclucte <iostream.h>
int main()

340

6: {
7: enum WeekDays { Sun, Mon, Tue,
8:

Wed, Thu, Fri, Sat, DaysInWeek } ;

9: int ArrayWeek[DaysInWeek] = { 10, 20, 30, 40, 50, 60, 70 }


10:

11:

cout << "The value at Tuesday is " << ArrayWeek[Tue];

12: return 0;
13: }

The value at Tuesday is 30

7 WeekDays, .
(Sunday) 0, DaysInWeek
7.
11 Tue
. Tue 2, 11
ArrayWeek[2].

, ,
, .
, .
1:
int MyIntegerArray[90]; ".
2:

'

long * ArrayOfPointersToLogs[ 100]; ,


, .
1:
Int theNinethlnteger = Mylntegeray[8];

'-'''i-.';- ;

2:
long * pLong = Array0fPointersToLogs[8J;
. , ,
, 0 - 1 .


, ,
. ,
.
, ,
, . ,
, ,
.

12.

341

- ,
, . ([])
, -
(.). 12.4
CAT.

12.4.
1: // 12.4.
2:
3: flinclude <iostream.h>

4:
5: class CAT

6: {
7: public:
8:

CAT() { itsAge = 1; itsWeight=5; }

9:

'CATO { )

10:

int GetAgeO const { return itsAge; }

11:
12:
13:

int GetWeightO const { return itsWeight; }


void SetAge(int age) { itsAge = age; }

14:

private:

15:

int itsAge;

16:
17: } ;

int itsWeight;

18:
19: int main()

20: {
21:

CAT Litter[5];

22: int i;
23: for (i = 0; i < 5; i++)
24:
Litter[i].SetAge(2*i +1);
25:
26:
27:

for (1 = 0; i < 5; i++)


{

28:
29:
30:

cout << "cat #" << i+1<< ": ";


cout << Litter[i ]. GetAgeO << endl;
}

31: return 0;
32: }

cat #1
cat #2
cat #3
cat #4
cat #5:

517 CAT. CAT


, -

342

, . , ,
.
for ( 23 24) ,
. for ( 2630)
, , GetAge().
GetAge() , ,
([])
(.), -.


, .
. ,
, ;
.. ,
, , .
,
, (. 12.3).

. 12.3.
, SQUARE.
Board :
SQUARE Board[8][8];

64 :
SQUARE Board[64];

,
,
. ,
.
:
Boa rd[0][3 ];

12.

343

,
, .
. 12.3.



. , ,
, . ,

int theArray[5][3];

theA[0],
theArray[1] ..
:
int theArray[5][3] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}:

,
, :
int theArray[5][3] = {{1,2,3},
{4,5,6},
{7,8,9},

{10,11,12},
{13,14,15}};

.
,
.
,
.
12.5.
0 4,
.

12.5. ____________________________________
1: flinclude <iostream.h>
2: int in()

3: {
4: int SomeArray[5][2] = { { 0,0} , { 1,2} , { 2,4} , { 3,6} , { 4,8} }
5: for (int i = 0; i<5; i++)
6:

for (int j=0; j<2; j++)

7:
8:

9:

cout << "SomeArray[" << i << "][" << j << "]: ";
cout << SomeArray[i][j]<< endl;

10 : }
11:

12: return 0;
13: }

344

[0][0]:

[0][1]:

8[1][0]:

[1][1]:

[2][0]:

8 2][1]: 4
8[3][0]:

5[3][1]:

[4][0]:

[4][1]: 8

4 .
, .
(5x2), . 12.4.

Some [5] [2]

. 12.4. 5x2
, .
f .
,
. :
SomeA[0][0], SomeAr[0][ 1 ].
, 1,
.


,
. ,
. ,
, . ,
64 , , 10
. , ,
.

, ,
.
, ,
C++ Unleashed, Sams Publishing.
, , ,
, , ,
.

12.

345


, ,
. ,
, .
,
, .
.
12.6 , 12.4,
.
,
5 500 Litter () Family ().

12.6.
1: // 12.6.
2:

3: include <iostream.h>
4:
5: class CAT
6: {

7: public:
8:
CAT() { itsAge = 1; itsWeight=5; }
9:
'CAT() { }
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20: {
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:

// destructor

int GetAge() const { return itsAge; }


int GetWeightO const { return itsWeight; }
void SetAge(int age) < itsAge = age; }
private:
int itsAge;
int itsWeight;
} ;
int rnainO
CAT
int
CAT
for

* Family[500];
i;
* pCat;
(i = 0; i < 500; i++)

{
pCat = new CAT;
pCat->SetAge(2*i +1);
Family[i] = pCat;
}
for (i = 0; l < 500; i++)
{
cout "Cat #" i+1 ";
cout << Family[i]->GetAge() endl;
}
return 0;
>

346

Cat #1: 1
Cat #2: 3
Cat #3: 5
Cat #499: 997
Cat #500: 999

CAT 517
12.4. , , 21
Family, 500
CAT.
( 2429)
500 CAT,
itsAge, . ,
CAT 1, 3, 5 ..
.
CAT*, ,
.
( 3135) ,
. :
Family[i], , GetAge().

. ,
.


.
new ,
, ,
:
CAT Family = new [500];

Family
CAT. ,
Fami 1[ 0 ].
,
Family
,
. , :
CAT Family = new [500];
CAT *pCat = Family; // pCat Family[0]
pCat->SetAge(10); // Family[0] 10
pCat++;

// Family[1]

pCat->SetAge(20); // Family[1] 20

500 CAT
. ,
SetAgeO, CAT,

12.

347

10.
,
20 .


:
1: Cat Family0ne[500];
2: CAT * FamilyTwo[500];
3: CAT * FamilyThree = new CAT[500];

FamilyOne, 500 CAT.


FamilyTwo, 500
CAT, FamilyThree, 500
CAT.
, ,
. ,
FamilyThree FamilyOne,
FamilyTwo.
, ,
. FamilyThree
, , FamilyOne.


C++
. ,
CAT Fami1[50];

Family &Fami]y[0].

. , Family + 4
Fami 1[ 4 ].

, , . Family +
4 ,
. ,
4, 16 .
CAT - long
- short ,
20 Family + 4 80 .

12.7.

348

12.7. n e w
1: // 12.7.

2:
3: include ciostream,h>
4:
5: class CAT
6: {
7: public:
8:

CAT() { itsAge = 1; itsWaight=5: }

9:

'CATO;

10;

int GetAgeO const { return itsAge; }

11:

int GetWeightO const { return itsWeight; }

12:

void SetAge(int age) { itsAge = age; }

13:
14: private:
15:

int itsAge;

16:

int itsWeight;

17: } ;
18:
19: CAT :: 'CATO

20: {
21: // cout << "Destructor called!\ n";

22 :

23:
24: int mainO
25: {
26: CAT * Family = new CAT[500];
27: int i;
28:
29: for (i = 0; i < 500; i++)
30: {
31:

Family[i].SetAge(2*i +1);

32: }
33:
34:

for (i = 0; i < 500; i++)

35:

36:

cout << "Cat #" << i+1 << ";

37:

cout << Family[i],GetAgeO << endl;

38: }
39:
40: delete [] Family;
41:
42: return 0;
43: }

12.

349

Cat #1: 1
Cat #2: 3
Cat #3: 5
Cat #499: 997
Cat #500: 999

26 Family CAT.
new [ 500]
.


CAT,
? ? Family
delete[ ] ( )
, .
,
.
, 500
10 26, 29 34. 21
cout . 43,
CAT Family.
-
new, delete,
.
new < c l a s s > [ s i z e ]
delete[]. ,
.
,
. ,
38.
21, ,
, .
!
.

0-1.

350

.

.


. ,
,
, cout, :
cout << "hello world.\n";

C++ ,
.
, , :
char Greeting[ ] = { , ' , , , '', ' ' , 'W.o.r'.'l'.'d', ' \ 0' };

(\0),
C++ .
,
, . , C++
:
char Greeting[] = "hello world";

,

.
.

,
.

Hello World 12 . Hello,


World .
. ,
, ,
, .
12.8 ,
, .

12.0.
1:

// 12.8.

2:
3:

include <iostream.h>

4:

5:

int main()

6:

7:

char buffer[80];

8:

cout << "Enter the string: ";

9:

cin >> buffer;

10: cout << "Here is the buffer: " << buffer << endl;
11:
return 0;
12 :

12.

351

||||| Enter the string: Hello World


Here's the buffer: Hello

7 buffer, 80 . 79 , ,
.
8 ,
buffer 9. cin
.
, 12.8,
. -, , 79 ,
cin , -, cin
, .
, get (),
cin: oin, get (). .
ttUky'1 f

.
12.9.

12..
1:

// 12.9. cin.get()

2:
3:

include <iostream.h>

4:
5:

int main()

6:
7;

char buffer[80]>

8:

cout << "Enter the string:

<

9:cin.get(buffer, 79); // 79
10:

cout << "Here's the buffer: " << buffer << endl;

11:

return 0;

12:

, , Enter the string: Hello World

Here's the buffer: Hello World

9 cin.get(). ,
'....' ......* 7, .
, 79 . 79
,
. .

.

352

strcpyO strncpyQ
C++ ,
. ,
. strcpyO strncpyQ.
strcpyO , 12.10.

12.10. s t r c p y O ___________________________________
1:

include <iostream.h>

2:

include <string.h>

3:

int main()

4:

5:

char St ring 1[ ] = "No man is an island";

6:

char String2[80];

7;
8:

strcpy(String2,St ring 1);

9:
10:

cout << "Stringl: " << Stringl endl;

11:

cout << "String2: " << String2 << endl;

12:

return 0;

13:

Stringl: No man is an island


String2: No man is an island

strin . h 2.
strcpyO.
, ,
. -
, strcpyO .
,
: strncpy().
, , . strncpyO
, .
strncpyO 12.11.

1 2 . 1 1 . s t ( ) ____________________________________
include ciostream.h>
include <string.h>
int main()

{
const int MaxLength = 80;
char Stringl[] = "No man is an island"
char String2[MaxLength+1];

12.

353

10: strncpy(String2,Stringl,MaxLength);

11:
12: cout << "Stringl: " Stringl << endl;
13: cout "String2: " << String2 endl;
14:

return 0;

15:

Stringl: No man is an island


String2: No man is an island

10 strcpyO
MaxLength
. String2 MaxLength+1.
,
strcpyO strncpyO.
strncpyO,


C++ ,
.
String.
C++
, strcpyO.
- . String
- -,
, ,
, .
String,
, , .
String
.
, String ,
. , .
.
,
. .

, ,
.
, .
String 12.12.

12.12. s t r i n g __________________________________________
1:

//.

12.12

2:
3:
4:

354

include <iostream.h>
include <string.h>

5:
6:

// string

7:

class String

8:
9:

{
public

10

//

11:

StringO

12:

Stnng(const char *const),

13:
14:

Stnng(const String &).


"StringO

15:
16:
17:

//
char & operatorf](unsigned short offset),

18:

char operator[](unsigned short offset) const,

19:

String operator+(const String&),

20:

void operator+=(const Stnng&)

21:

String & operator= (const String &),

22:
23:

//

24:

unsigned short GetLen()const { return itsLen, }

25:

const char * GetStnngO const { return itsString, }

26:
27:

private

28:

String (unsigned short), //

29:

char * itsString,

30:

unsigned short itsLen

31:

32:
33:// , no ,
34:

String StringO

35:
36:

{
itsString = new char[1]

37 :

itsStnng[0] = \ 0 ,

38:

itsLen=0,

39:

>

40:
41:

// ()

42:

//

43:

//

4:

String String(unsigned short len)

45:
46:

{
itsString = new char[len+1]

47:

for (unsigned short l = 0 i<=len, i++)

48:

itsStnng[i] = \ 0 ,

49:

itsLen=len,

50:
51:
52:

}
//

53:

String Stnng(const char * const cStnng)

54:

12.

355

55:

itsLen = strlen(cString);

56:

itsString = new char[itsl_en+1];

57:

for (unsigned short i = 0; i<itsLen: i++)

58:

itsString[i] = cSt ring[i ];

59:

itsString[itsLen]=\ O';

60:

61:
62:

// -

63:

String::String (const String & rhs)

64:

65:

itsLen=rhs.GetLen();

66:
67:

itsString = new char[itsLen+1 ];


for (unsigned short 1 = 0 ;

icitsLen;i++)

68:

itsString[i] = rhs[i];

69:

itsString[itsLen] = \ O';

70:

71:
72:

//

73:

String::"String ()

74:

75:
76:

delete [] itsString;
itsLen = 0;

77:

78:
79:

//

80:

// string size

81:

String& String::operator=(const String & rhs)

82:

83:

if (this == &rhs)

84:

return *this;

85:

delete [] itsString;

86:

itsLen=rhs.GetLen();

87:

itsString = new char[itsLen+1 ];

88:

for (unsigned short 1 = 0; KitsLen; i++)

89:

itsString[i] = rhs[i];

90:

itsString[itsLen] = 1\ O;

91:

return this;

92:

93:
94:

//

95:

// ,

96:

// !

97: char & String::operator[](unsigned short offset)


98:

99:

if (offset > itsLen)

100:

return itsString[itsLen-1];

101:
102:

else
return itsString[offset];

103:

104:

356

105://
106: //

(.

-!)

107: char String::operator[ ](unsigned short offset) const


108:
109:

{
if (offset > itsLen)

110:

return itsString[itsl_en-1];

111:
112:

else
return itsString[offset];

113:

114:
115:

//

116:
117:

// rhs
String String::operator+(const Strings rhs)

118:
119:

{
unsigned short totalLen = itsLen + rhs.GetLen();

120:

String temp(totalLen);

121:
122:

unsigned short i;
for ( i= 0; i<itsl_en; i++)

123:
temp[i] = itsString[i];
124: for (unsigned short j = 0; j<rhs.GetLen(): j++, i++)
125:

temp[i] = rhs[j];

126:

temp[totalLen]=\ 0;

127:

return temp;

128:
129:
130:

}
// void

131:

void String::operator+=(const String& rhs)

132:
133:

{
unsigned short rhsLen = rhs.GetLenO;

134:

unsigned short totalLen = itsLen + rhsLen;

135:

String temp(totalLen);

136:
137:

unsigned short i;
for (i = 0; KitsLen; i++)

138:
temp[i] = itsString[i];
139: for (unsigned short j = 0; j<rhs.GetLen(); j++, i++)
140:
141:

temp[i] = rhs[i-itsLen];
temp[totalLen]=\ 0;

142:

this = temp;

143:
144:

145:

int main()

146:
147:

{
String s1("initial test");

148:

cout << "S1:\ t" s1. GetStringO endl;

149:
150:

char * temp = "Hello World";

151:

s1 = temp;

152:

cout << "S1:\ t" s1 .GetStringO << endl;

153:
154:

char tempTwo[20];

12.

155:

strcpy(tempTwo,nice to be here!");

156:

s1 += tempTwo;

157:

cout "tempTwo:\ t" << tempTwo endl;

158:

cout "S1:\ t" s1.GetStringO endl;

159:
.160:

cout "SI[4]:\ t" << si[4] << endl;

161:

si[4]='o;

162:

cout "S1:\ t" s1.GetStringO endl;

163:
164:

cout "SI[999]:\ t" si[999] endl;

165:
166:

String s2(" Another string");

167:

String s3;

168:

s3 = s1+s2;

169:

cout << "S3:\ t" s3.GetString() << endl;

170:
171:

String s4;

172:

s4 = "Why does this work?";

173:

cout "S4:\ t" << s4. GetStringO << endl;

174:
175:

return 0;
}

S1:

initial

S1:

Hello

test
world

tempTwo: ; nice to be here!


S1: Hello world; nice to be here!
SI [4]:
S1: Hello World; nice to be here!
SI[999]: !
S3: Hello World; nice to be here! Another string
S4: Why does this work?

7-31 String. 1113 , -


( ).
String ([]), (+)
(+=). , char,
, char.
161:
SomeString[4]=';

.
, .
,
String, - 63. ,
rhs[i], rhs const String &.
, -.
.

358

, ,
, .
, .
, , 3339.
. , String
. , ,
, .
- 6370.

. -
.
5360 ,
. -.
strlen() String.
28 , String(unsigned short),
-. ,
String - .
String
, , , 131 operator+=.
, operator+=.
String(unsigned short)
NULL. for <=1, i<len.
, 7377, ,
String. , delete
. ,
, .
,
. ,
, . ,
, :
Stringl = String2 = St ;

.
. ,
, (1-1).
117128 (+)
. ,
:
St = Stringl + String2;

(+)
,
, NULL.
.
(*this), (rhs).
for
". for .
, ,
j rhs.
temp.

12.

359

temp ,
(stringl). +=
, stringl += string2.
+= , ,
temp , (this = temp), 142.
main() ( 145175)
. 147 String ,
. 148
GetString(). 150
. 151
, 152 .
154 tempTwo.
155 strcpyO
nice to be here!. 156 +=
tempTwo s1.
158.
160 s1.
161
([]). 162, ,
.
164 .
,
.
166 167 String, 168
. 169.
171 String s4. 172
, 173 .
, String,
21,
. ?
, String,
,
. 12 ,
String . String
.
.
, ,
.


.
,
.
, . ,
.

. ,
,

360

. , ,
, CAT Rectangle, , ,
, . ,
, ,
-.
. ,
.
.
.


.
. ,
, ,
: ... ,
...
. ,
.
. 12.5.


,
, ,
.


- ,

,
.
.
.
. . ,

, ,
.

,
.
: ,
.

12.

361

0 4

00

. 12.5.


.
.
.
. , .
( )
, , .
, .
,
, , .
,
.

.

362

12.13 ,
.

12.13.
0
1

II **********************************************

//

//

12.13.

//

// :

//

//

//

//

//

10

// .

11
12

// .

Copyright

()

1998

Liberty

Associates,

Inc.

// ,

13
14

// : ,

15
16

// .

17

// Data.

18

//

//

II

***********************************************

19

20
21
22

include <iostream.h>

23

enum { klsSmaller, klsLarger, klsSame} ;

24

//

26
27

// :

28

class

//

Show

25

Compare

Data

Data

29

30
31

public:
Data(int val):myValue(val){ }
"Data( ){ >

32

33

int Compare(const Data &);


void Show() { cout myValue endl; }

34'
35

private:

36
31
3.8
39

//

40

// .

41

int Data::Compare(const Data & theOtherData)

42

{'

int myValue;

};

43
44

if (myValue < theOtherData.myValue) .

45

if (myValue > theOtherData.myValue)

return klsSmaller;

12.

363

return klsLarger;

46:
47:

else

48:
49:

return klsSame;

50:
51:

//

52:

class Node;
class HeadNode;

53:
54:
55:

class TailNode;
class InternalNode;

56:
57:

// ADT- .

58:

// Insert Show

59:

class Node

60:

61:

public:

62:

Node(){ }

63:

virtual Node(){ }

64:

virtual Node * Insert(Data * theData)=0;

66:

virtual void Show() = 0;


private:

67:

};

65:

68:
69:

// .

70:
71:

// Data

72:

// ,

73:

class InternalNode: public Node

// 0 ,

74:

75:

public:

76:

InternalNode(Data * theData, Node * next);

77:

'InternalNode(){ delete myNext; delete myData; }

78:
79:

virtual Node * Insert(Data * theData);


virtual void Show() { myData->Show(); myNext->Show(); } // !

80:
81:

private:
Data * myData; //

82:
83:
84:

Node * myNext; //

};

85:

86:

// ,

87:

InternalNode::InternalNode(Data * theData, Node * next):

88:

myData(theData), myNext(next)

89:
90:

<
}

91:
92:

// .

93:

// ,

94:

//

95:

//

96: Node * InternalNode::Insert(Data * theData)


97: {
98:
99: // ?
100: int result = myData->Compare(*theData);

101:

102:
103: switch(result)
104: {
105:

// (lo , ,

106: case klsSame: //


107: case klsLarger: //
108: {
109:

InternalNode * dataNode = new InternalNode(theData, this);

110:

return dataNode;

111: }
112:
113:

// ,

114:

// , , .

115: case klsSmaller:


116:

myNext = myNext->Insert(theData);

117:

return this;

118: }
119: return this; // MSC

120: }

121:
122:
123: //
124:
125: class TailNode : public Node
126: {
127: public:
128: TailNode(){ }
129: "TailNode(){ }
130: virtual Node * Insert(Data * theData);
131: virtual void Show() { }
132:
133: private:

134:
135: > ;
136:
137: // , ,
138: //
139: Node * TailNode::Insert(Data * theData)
140: {
141: InternalNode * dataNode = ew InternalNode(theData, this);
142: return dataNode;
143: }
144:
145: // ,

12.

365

146:

//

147:

class HeadNode : public Node

148:

<

149:

public:

150: HeadNodeO;
151: "HeadNodeO { delete myNext; }
152: virtual Node * Insert(Data * theData);
153: virtual void Show() { myNext->Show(); }
154:

private:

155: Node * myNext:


156:
157:

} ;

158:

// ,

159:

//

160:

HeadNode::HeadNodeO

161:

162: myNext = new TailNode;


163:

>

164:
165:

// ,

166:

//

167:
168:

Node * HeadNode::Insert(Data * theData)


{

169: myNext = myNext->Insert(theData);


170: return this;
171:
172:

173:

//

174:

class LinkedList

175:'

176:

public:

177: LinkedList();
178: 'LinkedListO { delete myHead; }
179: void Insert(Data * theData);
180: void ShowAllO { myHead->Show(); }
181:

private:

182: HeadNode * myHead;


183:

} ;

184:
185:

// ,

186:

// ,

187:

// , ,

188:

// , , ,

.
189:
190:

LinkedList:: LinkedListO
<

191: ;myHead = new HeadNode;


192:'! }
193:
194:

366

// , ,

195: void LinkedList: :Insert(Data * pData)


196: {
197: myHead->Insert(pData);
198: }
199:
200: //
201 : int main()

202: {
203: Data * pData;
204: int val;
205: LinkedList 11;
206:
207: // ,
208: //
209: for (;;)
210: {
211:

cout "What value? (0 to stop): ";

212:

ein val;

213:
214:

if (! val)
break;

215:

pData = new Data(val);

216:
217: }

ll.Insert(pOata);

218:
219: //
220: ll.ShowAllO;
221: return 0; // 11 !

222: >

What value?
What value?

(0 to stop):
(0 to stop):

5
8

What value?

(0 to stop): 3
(0 to stop): 9

What value?

(0 to stop):

What value?

(0 to stop):

10

What value?

(0 to stop):

What value?

8
9

10

, , , 1511, ^ ^.
, , ().
, , .

12.

367

2837 Data, 39-49


Compare(). Data

Data. Show(),
Data.
,
, . 201
, 203 Data, 205
.
189 .
, , HeadNode
, 182.
HeadNode ,
160163, , , Tai 1 Node
myNext, HeadNode.
TailNode Tail Node, 128.
, .
,
,
,
, . 12.6.
209 .
, .
. 0 .
213.
, 215
Data, 216 . ,
15, 195 Insert.

. 12.6.

, 167 Insert.
( 139 Insert),
myNext.
(,
).
TailNode , ,
TailNode: Insert, . ,
141 InternalNode,
.
87 InternalNode.
InternalNode Data
, myNext

368

, .
, ,
, this.
, InternalNode,
dataNode 141,
TailNode: :Insert(). HeadNode: :Insert(),
InternalNode myNext HeadNode ( 169). ,
HeadNode , 197
( ,
).
, ?
Insert Node.
. HeadNode: :Insert(),
.
HeadNode .
- ? .
. ,
.
. ,
.
, myNext
. , , :
(. 12.7).
211
. ,
3. 215
Data 216.

. 12.7. ,

197 HeadNode.
HeadNode: :Insert(), , ,

myNext. , , Data
15. 96 InternalNode: :Insert().

12.

369

100 myData InternalNode (


15) Compare ),
Data 3. 41.
, , myValue
15, a theOtherData.myValue 3, klsLarger.

109.
InternalNode .
InternalNode, InternalNode
InternalNode: ;Insert() HeadNode. ,
, ,
, , . 12.8.
8. 3, 15,

. , ,
, CompareO Data,
3, klsSmaller, klsLarger,
( 3 8).
InternalNode: :Insert()
116. ,
Insert , myNext
. InsertNode ,
15.
,
.
, 15,
3, 116.

. 12.8. ,

.
,
,
.
.

370


, ,
.
. -

. , :
,
, .
,
. , -
, .
.
.
, ,
.
,
, .
, . , ,

. ,
, ,
, , .
? - -
. ,
.



. ,
,
.
, .
-

, :

:
;

: ;

: ,
;

: ,
. ,
] 8[-200],'
, ;

: ,
.

12.

371

([]),
.
, .
, .

, C++.
.
.
, .
0.
.
. ,
(, int)
, , .

, .
, delete[ ].

. ,
, .
,
.
,
, .
. C++
,
, .


, 24- 25- ?

, ,
.

?
, ,
, .
, , .

?
. , .
,
.

?
,
.

372

char *
?
. ,
.


,
.
, .
,
.


1. SomeArray[25]?
2. ?
3. ,
2.
4. SomeArray[10][5][20]?
5. ,
?
6. ?
7. ?

1. ,
.
2. , 0
.
3. Node, .
4. : ?
unsigned short SomeArray[5][4];
for (int i = 0; i<4; i++)
for (int j = 0; j<5; ]++)
SomeArray[i][j] = i+j;

5. : ?
unsigned short SomeArray[5][4];
for (int i = 0; i<=5; i++)
for (int j = 0; j<=4; j++)
SomeArray[i][j] = 0;

12.

373


,
.

. :


,
, - .
Bird, , Mammals, .
Bird - Fly(), . Mammals
, Horse. WhinnyO GallopO, .

(Pegasus), -
Horse Bird. , , ,
.
Pegasus Bird,
WhinnyO GallopO. Pegasus Horse,
Fly().
, Fly()
Horse, Pegasus. (Bird
Horse) Fly(),
.
, .
, ,
.

374

Bird Horse,
. , Pegasus
, .
.
, GallopO
Move(), Pegasus ,
Fly(). Horse Move()
, GallopO. Pegasus
, GallopO,
Fly :
Pegasus::Move(long distance)

{
if (distance > veryFar)
fly(distance);
else
gallop(distance);

}
,
. ,
Fly() Horse, 13.1? ,
, , ,
, Pegasus, .

13.1. ...
//

13.1. ...

// Fly() Horse
include <iostream.h>
class Horse

{
public:
void Gallop(){ cout << "Galloping...\ n"; }
virtual void Fly() { cout "Horses cant fly.\ n" ; }
private:
int itsAge;

> I
class Pegasus : public Horse

<
public:

virtual void Fly() { cout << "I can fly! I can fly! can
fly!\ n"; }

> ;
const int NumberHorses = 5;
int main()

{
Horse* Ranch[NumberHorses];

13.

375

25

Horse* pHorse; ,

26

int choice,i;

27

for (i=0; KNumberHorses; i++)

28

{
cout << "(1)Horse (2)Pegasus:

29
30

cin >> choice;


if (choice == 2)

31
32

pHorse = new Pegasus;

33

else

34

pHorse = new Horse;

35

Ranch[i] = pHorse;

36
37

}
cout << "\ n";

38

for (i=0; KNumberHorses; i++)

39

{
Ranch[i]->Fly();

40
41

delete Ranch[i];

42
43

}
return 0;

44

>

: (1)Horse

(2)Pegasus:

(1)Horse (2)Pegasus:

(1)Horse (2)Pegasus:

(1)Horse (2)Pegasus:

(1)Horse (2)Pegasus:

Horses cant fly.


I can fly! I can fly! I can fly!
Horses cant fly.
I can fly! I can fly! I can fly!
Horses cant fly.

, Horse
Fly(). 10.
, .
Pegasus 18 ,
, .
24 Horse,
Fly() . ,
,
.

376

,
,
. ,
.



,
. ,
, .
C++,
.
,

. , , Bird Horse
Animal, ,
, Eat(). Fly() ,
,
.


,
, Fly() ,
Pegasus.
, .
RTTI (Runtime Type Identification
). RTTI
C++.
RTTI,
, ,
.
Fly() ,
Pegasus.

,
,
.

, ,
.
Fly(),
, , Horse,
Pegasus. ,
Horse Pegasus.
, , C++,
dynamic_cast.
Horse
Pegasus,
. ,

dynamic_cast.

13.

377


. , ,
, ,
.
.
13.2.

13.2.
1://
2:
3

13 2 dynamic_cast
// rtti

4:

#include <iostream h>

5:

enurn TYPE { HORSE, PEGASUS } ,

6:
7'

class Horse

8'

9.

public

10:virtual void Gallop(){ cout "Galloping...\n"; >


11:
12:
private13:

int itsAge;

14:
15.

> ,

16:

class Pegasus : public Horse

17:

18:
19:

public:

20:virtual void Fly() { cout "I can fly! I can fly! I can fly!\ n"; }
21:
22:

} ;

23.
24:

const mt NumberHorse = 5,
mt main()

25:

26'

Horse* Ranch[NumberHorse];

27:

Horse* pHorse;

28:

int choice,l,

29:
30:

for (i=0: i<NumberHorse, i++)


{

31:

cout "(1)Horse (2)Pegasus:

32:

cin choice;

33.

if (choice == 2)

34:

pHorse = new fegasus;

35:

else

36:

pHorse = new Horse;

37:

Ranch[i] = pHorse,

38:

39:

cout << "\ n";

40:
41:

for (i=0; -KNumberHorses; i++)


{

42.Pegasus *pPeg = dynamic_cast< Pegasus *> (Ranch[ij);

378

4.2

if (pPeg)

43
44

else

45
46
47

pPeg->Fly();
cout "Just a horse\ n";
delete Ranch[i];

48
49
50

return 0;

(1)Horse (2)Pegasus: 1
(1)Horse (2)Pegasus:

(1)Horse (2)Pegasus:

(1)Horse (2)Pegasus:

(1)Horse {2)Pegasus:

Just a horse
I can fly! I can fly! I can fly!
Just a horse
I can fly! I can fly! I can fly!
Just a horse.


4541: <dynamic_cast'
used on polymorphic type class Horse with/GR-; unpredictable behavior may result
?
MFC .
, .
1.
2.
3.
4.
5.

ProjectoSettings.
C/C++.
Category C++ Language.
Enable Runtime Type Information (RTTI).
.

Fly() Horse

. Pegasus,
,
, .
,
. ,
,
.

13.

379


, Pegasus Horse
Bi rd.
Fly ( ) , ,
.
, ,
. Fly( ),
WhinnyO GallopO Animal,
Bird Horse. Bird Horse
Animal. ,
.
, ,
Horse, Bird Pegasus,
!


.
,

.
,
.



. .
, . 13.3
Pegasus ,
Bird Horse. Pegasus .

13.3. __________
1:

// 13.3. .

2:

//

3:
4:

include ciostream.h>

5:
6:

class Horse

7:
8:

{
public:

9:
10:

Horse() { cout << "Horse constructor... }


virtual "HorseO { cout << "Horse destructor..

11: virtual void WhinnyO const { cout << "Whinny!

380

12: private:
13: int itsAge;
14: } ;
15:
16: class Bird
17: {
18: public:
19: Bird() { cout "Bird constructor... }
20: virtual Bird() { cout << "Bird destructor... }
21: virtual void ChirpO const { cout << "Chirp... }
22: virtual void Fly() const
23: {
24: cout << "I can fly! I can fly! I can fly!
25: }
26: private:
27: int itsWeight;
28: } ;
29:
30: class Pegasus : public Horse, public Bird
31: {
32: public:
33: void Chirp() const { WhinnyO; }
34: PegasusO i cout << "Pegasus constructor... }
35: 'PegasusO { cout << "Pegasus destructor... }
36: } ;
37:
38: const int MagicNumber = 2;
39: int main()
40: {
41: Horse* Ranch[MagicNumber];
42: Bird* Aviary[MagicNumber];
43: Horse * pHorse;
44: Bird * pBird;
45: int choice,i;
46: for (i=0; KMagicNumber; i++)
47: {
48: cout << "\ n(1)Horse (2)Pegasus:
49: cin >> choice;
50: if (choice == 2)
51:

pHorse = new Pegasus;

52: else
53:

pHorse = new Horse;

54: Ranch[i] = pHorse;


55: }
56: for (i=0; KMagicNumber; i++)
57: {
58: cout << "\ n(1)Bird (2)Pegasus: ";
59: cin >> choice;
60: if (choice =- 2)
61:

pBird = new Pegasus;

13.

381

else
pBird = new Bird;

62:
63:

Aviary[i] = pBird;

64:
65:

>

66:
(67:

cout "\ n";


for (i=0; i<MagicNumber;

68:
69:
70:

{
cout "\ nRanch[" <<

71:

Ranch[i]->Whinny();

i++)
i "]:

delete Ranch[i];

72:
73:

>

74:
75:

for (i=0; i<MagicNumber;

i++)

76:
77:

{
cout << "\ nAviary["

i "]

78:

Aviary[i]->Chirp();

79:

Aviary[i]->Fly();
delete Aviary[i];

80:
81:
82:
83:

}
return 0;
}

(1)Horse (2)Pegasus: 1
Horse constructor...
(1)Horse (2)Pegasus: 2
Horse constructor... Bird constructor... Pegasus constructor...
(1)Bird (2)Pegasus: 1
Bird constructor...
(1)6ird (2)Pegasus: 2
Horse constructor... Bird constructor... Pegasus constructor...
Ranch[0]: Whinny!... Horse destructor...
Ranch[1]: Whinny!... Pegasus destructor... Bird destructor...
Horse destructor...
Aviary[0]: Chirp... I can fly! I can fly! I can fly! Bird destructor...
Aviary[1]: Whinny!... I can fly! I can fly! I can fly!
Pegasus destructor... Bird destructor... Horse destructor...

614 Horse.
, WhinnyO Whinny!

(--).
Bird 1628.
: Chi() Fly(),
.

.

382

, 30-36 Pegasus.
Bird Horse. Chi() ,
WhinnyO, Horse.
: Ranch (), 41
Horse, Aviary (), 42 Bird.
46-55 Ranch Horse Pegasus. 56-65
Aviary Bird Pegasus.
Bird Horse
Pegasus. , 78 Chi()
,
Aviary. Bird ,
.
,
Pegasus Bird, Horse Pegasus,
.
, Bird Horse,
.


,
, ,
.
1:
dass Pegasus : public Horse, public Bird

2:
class Schnoodle : public Schnauzer, public Poodle

,

Pegasus,
, . 13.1.
/

/
Horse

/
Bird

/
Pegasus

. 13.1. ,

13.

383


. , ,

? ?
,
? ,
.

,

Pegasus Bird Horse,
, Pegasus
. , 13.4.

13.4.
1

// 13.4.

//

ffinclude

typedef int HANDS;


enum COLOR { Red, Green, Blue, Yellow, White, Black, Brown };

<iostream.h>

6
7

class

public:

10

Horse

Horse(C0L0R

color,

HANDS

height);

11
12

virtual "HorseO { cout << "Horse destructor. . n"; }


virtual

void

Whinny()const

13

virtual

HANDS

GetHeightO

const

14

virtual

COLOR

GetColorO

15
16

"Whinny!...

return

return

";

itsHeight;

itsColor;

private:
HANDS itsHeight;
COLOR itsColor;

17
18

const

cout

};

19

20

Horse::Horse(C0L0R color, HANDS height):

21
22

itsColor(color),itsHeight(height)

{
cout << "Horse constructor..,\ n";

23
24

25
26

class

27

Bird

28
29

public:
Bird(C0L0R

30

virtual

"Bird()

31

virtual

void

32

virtual void Fly()const

color,
{

bool

migrates);

cout

ChirpQconst

"Bird
{

cout

destructor..,\
<<

"Chirp...

n";
";

33

384

34:

cout << "I can fly! I can fly! I can fly!

35:

36:virtual COLOR 6etColor()const { return itsColor; }


37: virtual

bool

GetMigration()

const

return

38:
39:
40:
41:

private:
COLOR itsColor;
bool itsMigration;

42:

} ;'

43:
44:

Bird::Bird(C0L0R color, bool migrates):

45:

itsColor(color), itsMigration(migrates)

46:

47:

cout << "Bird constructor...\ n";

48:

49:
50:

class Pegasus : public Horse, public Bird

51:

52:

public:

53:
54:

void ChirpQconst ( Whinny O; }


Pegasus(C0L0R, HANDS, bool,long);

55:PegasusO { cout << "Pegasus destructor. .. \ n";>


56:
57:

virtual long GetNumberBelieversO const


{

58:

return itsNumberBelievers;

59:

60:
61:

private:

62:

long itsNumberBelievers;

63:

} ;

64:
65:

Pegasus::Pegasus(

66:
67:

COLOR aColor,
HANDS height,

68:

bool migrates,

69:
70:

long NumBelieve):
Horse(aColor, height),

71:

Bird(aColor, migrates),

72:

itsNumberBelievers(NumBelieve)

73:

74:

cout << "Pegasus constructor..,\ n";

75:

76:
77:

int main()

78:

79: Pegasus *pPeg = new Pegasus(Red, 5, true, 10);


80:
81:

pPeg->Fly();
pPeg->Whinny();

82:cout << \ nYour Pegasus is " pPeg->GetHeight();


83:

cout << " hands tall and ";

13.

itsMigration;

84:

if (pPeg->GetMigration())

85:

cout << "it does migrate.";

86:

else

87:

cout << "it does not migrate.";

88:cout << "\ nA total of " << pPeg->GetNumberBelievers();


89:

cout << " people believe it exists.\ n";

90:

delete pPeg;

91:

return 0;

92:

*'*

r Horse constructor...
Bird constructor...
Pegasus constructor...
I can fly! I can fly! I can fly! Whinny!...
Your Pegasus is 5 hands tall and it does migrate.
A total of 10 people believe it exists.
Pegasus destructor...
Bird destructor...
Horse destructor...

Horse 718.
: , 5,
, typedef 4.
2024. -
Horse.
2642 Bird,
4549. .
;
,
. , ,
, .
Pegasus 5063, 6575.
Pegasus .
Horse . Bird
. ,
- itsNumberBelievers, Pegasus.
Pegasus.
main() Pegasus,
- .


13.4 Horse Bird GetColor().
Pegasus, ;
? ,
, .
,
.

386

:
COLOR currentColor = pPeg->GetColor();

Member is ambiguous: Horse: :GetColor and


' Bird : :GetColor' ( ).
, ,
:
COLOR currentColor = pPeg->Horse::GetColo();

,
- ,
.
Pegasus ,
, - Pegasus:
virtual COLOR GetColor()const { return Horse::GetColor(); }

,
.
,
.
COLOR currentColor = pPeg->Bird::GetColo ( ) :


, , ,
, , ,
Bird Horse Animal. . 13.2.

. 13.2.
. 13.2, , Pegasus,
Animal.
Bird Horse ,

13.

387

. , Animal
- itsAge - GetAgeO,
pGet->GetAge( ), GetAgeO,
Bird Animal Horse ?
13.5.

13.5. 8
1:

// 13.5.

2;

//

3:

include <iostream.h>

4:
5:

typedef int HANDS;

6: enum COLOR { Red, Green, Blue, Yellow, White, Black, Brown >
7:
8: class Animal // horse bird
9:
10:

{
public:

11:

Animal(int);

12: virtual "AnimalO { cout << "Animal destructor. ..\ n"; }


13:
virtual int GetAgeO const { return itsAge; >
14:

virtual void SetAge(int age) { itsAge = age; >

15:

private:

16:

int itsAge;

17:

> ;

18:
19:

Animal::Animal(int age):

20:

itsAge(age)

21:

22:

cout << "Animal constructor..,\ n";

23:
24:

>

25:

class Horse : public Animal

26:
27:

{
public:

28:

Horse(C0L0R color, HANDS height, int age);

29:

virtual "HorseO { cout << "Horse destructor. . n"; }

30:

virtual void Whinny()const { cout << "Whinny!... "; >

31:

virtual HANDS GetHeightO const { return itsHeight; }

32:

virtual COLOR GetColorO const { return itsColor; }

33:

protected:

34:

HANDS itsHeight;

35:

COLOR itsColor;

36:

} ;

37:
38:

Horse::Horse(C0L0R color, HANDS height, int age):

39:
40:

Animal(age),
itsColor(color),itsHeight(height)

41:

42:

cout << "Horse constructor..,\ n";

388

43:

44:
45:

class Bird : public Animal

46:
47:

{
public:

48:
49:

Bird(COLOR color, bool migrates, int age);


virtual "Bird() { cout << "Bird destructor...\ n"; }

50:

virtual void Chirp()const { cout << "Chirp... "; }

51:

virtual void FlyOconst

52:

{ cout << "I can fly! I can fly! I can fly! }

53:

virtual COLOR GetColor()const { return itsColor; )

54:

virtual bool GetMigration() const { return itsMigration; }

55:

protected:

56:
57;

COLOR itsColor;
bool itsMigration;

58:

) ;

59:
60:

Bird::Bird(C0L0R color, bool migrates, int age):

61:
62:

Animal(age),
itsColor(color), itsMigration(migrates)

63:
64:

{
cout << "Bird constructor...\ n";

65:

66:
67:

class Pegasus : public Horse, public Bird

68:

69:

public:

70:

void Chirp()const { WhinnyO; >

71:

Pegasus(C0L0R, HANDS, bool, long, int);

72:

virtual "PegasusO { cout "Pegasus destructor. ..\ n";}

73:

virtual long GetNumberBelievers() const

74:

{ return itsNumberBelievers; }

75:
76:

virtual COLOR GetColor()const { return Horse::itsColor; >


virtual int GetAge() const { return Horse::GetAge(); }

77:
78:

private:
long itsNumberBelievers;

79:

} ;

80:
81:

Pegasus::Pegasus(

82:

COLOR aColor,

83:

HANDS height,

84:

bool migrates,

85;

long NumBelieve,

86:

int age):

87:

Horse(aColor, height,age),

88:

Bird(aColor, migrates,age),

89:

itsNumberBelievers(NumBelieve)

90:

91:

cout "Pegasus constructor..,\ n";

92:

13.

93:
94:

int main()

95:

96:

Pegasus *pPeg = new Pegasus(Red. 5, true, 10, 2);

97:

int age = pPeg->GetAge();

98:

cout << "This pegasus is " << age << " years old.\ n";

99:

delete pPeg;

100:

return 0;

101:

Animal constructor...
Horse constructor...
Animal constructor...
Bird constructor...
Pegasus constructor...
This pegasus is 2 years old.
Pegasus destructor...
Bird destructor...
Animal destructor...
Horse destructor...
Animal destructor...

. , 817
Animal - itsAge
GetAgeO SetAgeO.
25 Horse Animal. Horse
, Animal.
, Horse GetAgeO , .
46 Bird Animal.
,
Animal. GetAgeO .
Pegasus Horse Bird,
Animal .
Animal GetAgeO,
, ,
GetAgeO Pegasus.
GetAgeO Pegasus
,
.

. -,
; -, ,

, .

, .
Pegasus : ,
( ); , ,
; , ,

390

. 87 ,
Horse (, ). ,
Bird: , . , 89
itsNumberBelievers, Pegasus.
Horse 87 ,
38. Horse
itsAge, Horse Animal.
- Horse itsColor itsHeight.
Bird 88 ,
60.
-, Bird Animal.
, Pegasus
- , Bird Horse.
itsAge ,
Animal.


13.5 , :
getAgeO Pegasus.
Animal.
C++ ,
, . 13.2, (. 13.3).

. 13.3.
Animal
, Horse Bird. Animal .
Horse Bird ,
Animal. Pegasus .

- . ,
.

13.

391

, ,
. Animal
Horse Bird, Pegasus.
Horse Bird
Animal, Pegasus
.
13.6 13.5,
,
.

. 13.#. __________________________
1:

//

13.6.

2:

//

3:

include <iostream.h>

4:
5:

typedef int HANDS;

6:enum COLOR { Red, Green, Blue, Yellow, White, Black, Brown } ;


7:
8:class Animal // horse bird
9;
10:

{
public:

11:
12:

Animal(int);
virtual 'Animal() { cout "Animal destructor...\ n"; }

13:

virtual int GetAgeO const { return itsAge; }

14:

virtual void SetAge(int age) { itsAge = age; )

15:

private:

16:

int itsAge;

17:

} ;

18:
19:

Animal::Animal(int age):

20:

itsAge(age)

21:

22:

cout << "Animal constructor...\ n";

23:

24:
25:

class Horse : virtual public Animal

26:

27:

public:

28:

Horse(C0L0R color, HANDS height, int age);

29:

virtual "Horse() { cout "Horse destructor.. n"; }

30:

virtual void Whinny()const { cout "Whinny!... "; }

31:

virtual HANDS GetHeightO const { return itsHeight; }

32:

virtual COLOR GetColor() const { return itsColor; }

33:

protected:

34:

HANDS itsHeight;

35:

COLOR itsColor;

36:

} ;

37:
38:

Horse::Horse(C0L0R color, HANDS height, int age):

39:

Animal(age),

392

40:

itsColor(color),itsHeight(height)

41:

42:

cout "Horse constructor..,\ n";

43:

44:
45:

class Bird : virtual public Animal

46:
47:
48:

{
public:
Bird(C0L0R color, bool migrates, int age);

49: virtual "Bird() { cout << "Bird destructor..,\ n"; }


50:

virtual void Chirp()const { cout << 'Chirp... "; >

51:

virtual void FlyQconst

52:

{ cout "I can fly! I can fly! I can fly! "; }

53:

virtual COLOR GetColor()const { return itsColor; }

54:virtual bool GetMigration() const { return itsMigration; }


55:

protected:

56:

COLOR itsColor;

57:

bool itsMigration;

58:

} ;

59:
60:

Bird::Bird(C0L0R color, bool migrates, int age):

61:

Animal(age),

62:

itsColor(color), itsMigration(migrates)

63:

64:

cout << "Bird constructor...\ n";

65:

66:
67:

class Pegasus : public Horse, public Bird

68:

69:

public:

70:

void Chirp()const { WhinnyO; >

71:

Pegasus(C0L0R, HANDS, bool, long, int);

72:virtual ~Pegasus() { cout << "Pegasus destructor. .. \ n";}


73:
74:

virtual long GetNumberBelievers() const


{ return itsNumberBelievers; }

75:virtual COLOR GetColor()const { return Horse::itsColor; }


76:
77:

private:
long itsNumberBelievers;

78:

> ;

79:
80:

Pegasus::Pegasus(

81:

COLOR aColor,

82:

HANDS height,

83:

bool migrates,

84:

long NumBelieve,

85:
86:
87:

int age):
Horse(aColor, height,age),
Bird(aColor, migrates,age),

88:

Animal(age*2),

89:

itsNumberBelievers(NumBelieve)

13.

90: {
91: cout << "Pegasus constructor...\ n";
92: }
93:
94: int main()
95: {
96: Pegasus *pPeg = new Pegasus(Red, 5, true, 10, 2);
97: int age = pPeg->GetAge();
98: cout << "This pegasus is " << age << " years old.\ n";
99: delete pPeg:
100: return 0;

101: }

Animal constructor...
Horse constructor...
Bird constructor. . .
Pegasus constructor...
This pegasus is 4 years old.
Pegasus destructor...
Bird destructor.. .
Horse destructor...
Animal destructor...

25 Horse Animal,
45 Bird. ,
- Animal.
Pegasus, Animal,
. ,
. itsAge
2, Pegasus .
98 4.
Pegasus
, GetAgeO
Animal. GetColorO -
, , Horse Bird.



, .
, ++
; , ,
, .
,
, ,
, ,
.

394


,
,
.
1:
dass

Horse

virtual

public

Animal

class Bird : virtual public Animal

dass Pegasus : public Horse, public Bird

2:
class

Schnauzer

virtual

public Oog

class Poodle ; virtual public Oog


class Schnoodle : public Schnauzer, public

Poodle

,
,
.

,

.

,

.


,
.

^.

Horse

Animal Displayable,
.
- , ,
(, ,
).
-
. -
, .
, ,

. -
,
.

13.

395

, , Horse Animal
Displayable, ,

. Horse
Animal, .
- (capability class) (mixin).
,
, .
Sommerville . , -
, -
SCOOPS, .



. , Shape,
Rectangle Circle. Rectangle Square,
.
Draw(), GetAreaO .
Shape Rectangle Circle
13.7.

161 13.7. Shipi_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _


1:

// 13.7. Shape

2:
3:

include <iostream.h>

4:
5:
6:

class Shape

7:
8:

{
public:

9:
10:

Shape(){ >
virtual 'Shape(){ >

11:

virtual long GetAreaO { return -1; >

12:

virtual long GetPerimO < return -1; }

13:

virtual void Draw() { }

14:

private:

15:

} ;

16:
17:

class Circle : public Shape

18:

<

19:
20:

public:
Circle(int radius):itsRadius(radius){ }

21:
"Circle(){ }
22:long GetAreaO { return 3 * itsRadius * itsRadius; }
23:

long GetPerimO { return 6 * itsRadius; }

24:

void Draw();

25:

private:

26:

int itsRadius;

396

27:

int itsCircumference;

28: } ;
29:
30: void Circle::Draw()
31: {
32: cout << "Circle drawing routine here!\ n";
33: }
34:
35:
36: class Rectangle : public Shape
37: {
38: public:
39:

Rectangle(int len, int width): ,-

40:

itsLength(len), itsWidth(width){ >

41:

virtual 'Rectangle() { }

42:

virtual long GetArea() { return itsLength * itsWidth; }

43:

virtual long GetPerim() < return 2*itsLength + 2*itsWidth;

44:

virtual int Getlength() { return itsLength; }

45:

virtual int GetWidth() { return itsWidth; }

46:

virtual void Draw();

47: private:
48: int itsWidth;
49:

int itsLength;

50: } ;
51:
52: void Rectangle::Draw()
53: {
54:

for (int i = 0; icitsLength; i++)

55: {
56:

for (int j = 0; jcitsWidth; j++)

57:

cout << "x ";

58:
59:

cout "\ n";

60: >
61: >
62:
63: class Square : public Rectangle
64: {
65: public:
66:

Square(int len);

67:

Square(int len, int width);

68:

~Square(){ }

69:

long GetPerim() { return 4 * GetLength();}

70: } ;
71:
72: Square::Square(int len):
73:
Rectangle(len,len)
74: { }
75:
76: Square::Square(int len, int width):

13.

Rectangle(len,width)

77:
78:
79:
80:

if (GetLength() != GetWidthO)
cout << "Error, not a square... a Rectangle??\ n";

81:
82:

83:
84:

int main()

85:

{
int choice;

86 :
87:

bool fQuit = false;

88:

Shape * sp;

89:
90:

while ( ! fQuit )

91:

92:

cout << "(1)Circle (2)Rectangle (3)Square (0)Quit:";

93:

cin choice;

94:
switch (choice)

95:
96:

<

97:

case 0: fQuit = true;


break;

98:
99:

case 1: sp = new Circle(5);


break;

100:
101 :
102 :

case 2: sp = new Rectangle(4,6);


break;
case 3: sp = new Square(5);

103:
104:

break;

105:

default: cout << "Please enter a number between 0 and 3 << endl;

106:
107:

continue;
break;

108:
109:
110 :

if(! fQuit)
sp->Draw();

111:

delete sp;

112 :

cout << "\ n;

113:
114:

>
return 0;

115:

(1)Circle (2)Rectangle (3)Square (0)Quit: 2


x x x x x x
x x x x x x
x x x x x x
X X X X X X

(1)Circle (2)Rectangle (3)Square (0)Quit:3


x x x x x

X X X X X
X X X X X
X X X X X
X X , X X

(1)Circle (2)Rectangle (3)Square (0)Quit:0

615 Shape. GetAreaO GetPerimO


-1 , Draw()
. , ?
, ,
, .
Ci rcle Shape,
. ,
V i r t u a l ,
.
.
Square Rectangle ,
GetPerimO .
,
Shape, .

. Shape , ,
,
, ADT (Abstract Data Type).
, ,
, . C++ ADT
,
.


C++
. ,
, :
Virtual void Draw() = 0;

, , ADT.
, ADT.
.
:

, ADT,
, ,
. , Rectangle Shape,
, Rectangle
, ADT. 13.8 -

13.

399

ca Shape , .
13.7 , .
7-16 13.7 13.8 .

13.1. |______________________________________
1:

Shape

2:

3:

public:

4:

Shape(){ }

5:
6:

'Shape(){ ) .
virtual long GetArea() = 0: //

7:

virtual long GetPerim()= 0;

8:

virtual void Draw() = 0;

9:

private:

10:

};

81

(1)Circle

(2)Rectangle

(3)Square

(O)Quit:

(3)Square

(O)Quit:

x x x x x x
x x x x x x
x x x x x x
x x x x x x
(1)Circle

(2)Rectangle

x x x x x
x x x x x
x x x x x
x x x x x
X X X X X

(1)Circle (2)Rectangle (3)Square (O)Quit: 0

, .
Shape.


,
.
- , .

virtual void DrawO = 0; //

Vv-

%&'7W0 :

400



.
, , ff
. ADT ,
.

. , ADT,
.
13.9 13.7, Shape
ADT Draw().
Circle,
,
.
.

.
, ,
, .

13.9.
1

//

include

<iostream.h>

4
5

class

Shape

public :
Shape( ){ }

8
9

virtual ~Shape(){ }
10
virtual long
11
virtual long

GetAreaO =
GetPerim()=

0;
0;

virtual void Draw() = 0;

12
13
14

private :
};

15
16

void Shape : :Draw()

17

{
cout << "Abstract drawing mechanism!\ n";

18
19

20

21

class Circle : public Shape

22

23
24

public :

25

Circle(int

radius):itsRadius(radius){

virtual ~Cirole( ){ }

26

long GetAreaO { return 3 * itsRadius * itsRadius; }

27

long GetPerim() { return 9 * itsRadius; }

13.

401

28: void Draw();


29: private:
30: int itsRadius;
31: int itsCircumference;
32: } ;
33:
34: void Circle::Draw()
35: {
36: cout "Circle drawing routine here!\ n";
37: Shape::Draw();
38: }
39:
40:
41: class Rectangle : public Shape
42: {
43: public:
44: Rectangle(int len, int width):
45:

itsLength(len), itsWidth(width){ }

46: virtual "Rectangle(){ }


47: long GetArea() { return itsLength * itsWidth; }
48: long GetPerim() { return 2*itsLength + 2*itsWidth: }
49: virtual int GetLength() { return itsLength; }
50: virtual int GetWidth() { return itsWidth; }
51: void Draw();
52: private:
53: int itsWidth;
54: int itsLength;
55: } ;
56:
57: void Rectangle::Draw()
58: {
59: for (int i = 0; i<itsLength; i++)
60: {
61: for (int ] = 0; j<itsWidth; j++)
62:

cout << "x ";

63:
64: cout << "\ n";
65: }
66: Shape::Draw();
67: }

68:
69;
70; class Square : public Rectangle

71: {
72: public:
73: Square(int len);
74: Square(int len, int width);
75: virtual 'Square(){ }
76: long GetPerim() { return 4 * GetLengthO;)
77: } ;

402

78:
79: Square::Square(int len):
80: Rectangle(len,len)
81: { }
82:
83: Square::Square(int len, int width):
84: Rectangle(len,width)
85:

86: {
87: if (GetLengthO != GetWidthO)
88: cout << "Error, not a square... a Rectangle??\ n";
89: }
90:
91: int main()
92: {
93: int choice;
94: bool fQuit = false;
95: Shape * sp;
96:
97: while (1)
98: {
99:

cout

<<

"(1)Circle

(2)Rectangle

(3)Square

(O)Quit:

";

100: cin >> choice;

101 :
102: switch (choice)
103: {
104: case 1: sp = new Circle(5);
105: break;
106:

case 2: sp = new Rectangle(4,6);

107: break;
108: case 3: sp = new Square (5);
109: break;
110:

default: fQuit = true;

111:

break;

112: }
113: if (fQuit)
114:
break;
115:
116: sp->Draw();
117: delete sp;
118; cout "\ n";
119: }
120: return 0;

121 : }

(1)Circle (2)Rectangle (3)Square (0)Quit: 2


x x x x x x
x x x x x x
x x x x x x

13.

403

Abstract drawing mechanism!


(1 )Circle (2)Rectangle (3)Square (O)Quit: 3
X X X X X
X X X X X
X X X X X
X X X X X
X X X X X

Abstract drawing mechanism!


(1)Circle (2)Rectangle (3)Square (O)uit: 0

514 Shape
. ,
ADT,
.

Ci rcle Rectangle, Draw()
,
.

.


ADT ADT,
, ADT
, ,
.
, Animal Eat(), SI( ), Move() ReproduceQ
. Animal
Mammal Fish.
,
, Mammal ReproduceQ ,
EatQ, SleepQ MoveQ .
Mammal Dog,
,
Dog.
, ADT ADT
,
.
13.10 ,
.

13.10. __________________________
1 : // 13.10.

2:

// Deriving ADTs from other ADTs

3:

ftinclude <iostream.h>

4:

5:

404

enum C0L0R { Red, Green, Blue, Yellow, White, Black, Brown } ;

6:
7:class Animal // Mammal Fish

8:

<

9:

public:

10:

Animal(int);

11: virtual 'Animal() { cout << "Animal destructor...\ n"; }


12:
13:

virtual int GetAgeO const { return itsAge; >


virtual void SetAge(int age) { itsAge = age; }

14:

virtual void SleepO const = 0;

15:

virtual void Eat() const = 0;

16:

virtual void ReproduceO const = 0;

17:

virtual void Move() const = 0;

18:

virtual void Speak() const = 0;

19:

private:

20:

int itsAge;

21:

} ;

22:
23:

Animal::Animal(int age):

24:
25:

itsAge(age)
{

26:

cout << "Animal constructor...\ n";

27:

>

28:
29:

class Mammal : public Animal

30:

31:

public:

32:

Mammal(int age):Animal(age)

33:

{ cout << "Mammal constructor...\ n";}

34: virtual 'MammalO { cout << "Mammal destructor. .. \ n";>


35:

virtual void ReproduceO const

36:

{ cout << "Mammal reproduction depicted...\ n"; }

37:

} ;

38:
39:
40:

class Fish : public Animal


{

41:

public:

42:
43:

Fish(int age):Animal(age)
{ cout << "Fish constructor...\ n";)

44:

virtual "Fish() { cout << "Fish destructor...\ n"; }

45:virtual void SleepO const { cout << "fish snoring...\ n"; }


46:virtual void Eat() const { cout << "fish feeding...\ n"; }
47:

virtual void ReproduceO const

48:

{ cout << "fish laying eggs...\ n"; }

49:

virtual void Move() const

50:

{ cout << "fish swimming...\ n"; }

51:
52:

virtual void Speak() const { }


} ;

53:
54:

class Horse : public Mammal

55:

13.

405

56:

public:

57:

Horse(int age, COLOR color ):

58:

Mammal(age), itsColor(color)

59:

{ cout << "Horse constructor..,\ n"; }

60:

virtual ~Horse() { cout << "Horse destructor, .. \ n"; }

61:

virtual void Speak()const { cout << "Whinny!... \ n"; }

62:

virtual COLOR GetltsColorQ const { return itsColor; }

63:
64:

virtual void Sleep() const


{ cout << "Horse snoring...\ n"; }

65:

virtual void Eat() const { cout "Horse feeding...\ n"; }

66:

virtual

void

Move()

const

cout

<<

"Horse

running...\

n";>

67:
68:

protected:

69:

COLOR itsColor;

70:

} ;

71:
72:

class Dog : public Mammal

73:

<

74:

public:

75:

Dog(int age, COLOR color ):

76:

Mammal(age), itsColor(color)

77:

{ cout "Dog constructor...\ n"; }

78:

virtual 'Dog() { cout << "Dog destructor...\ n"; }

79:

virtual void Speak()const { cout << "Woof!... \ n"; }

80:

virtual void Sleep() const { cout << "Dog snoring...\ n"; }

81:

virtual void Eat() const < cout "Dog eating...\ n"; }

82:

virtual void Move() const { cout << "Dog running...\ n"; }

83:

virtual void Reproduce() const

84:

{ cout "Dogs reproducing..,\ n"; }

85:
86:

protected:

87:

COLOR itsColor;

88:

};

89:
90:
91:

int main()
{

92:

Animal *pAnimal=0;

93:

' int choice;

94:

bool fQuit = false;

95:
96:.
9,7:

while (1)
, {

98:

cout << "(1)Dog (2)Horse (3)Fish (O)Quit: ";

99:

cin >> choice;

100:
101:

switch (choice)

102:

103:
104:

case 1: pAnimal = new Dog(5,Brown);


break;

105:

case 2: pAnimal = new Horse(4,Black);

406

break;

106
107

case 3: pAnimal = new

108

break;

109

default: fQuit = true


break;

110
111

}
if (fOuit)

112

break;

113
114
115

pAnimal->Speak();

116

pAnimal->Eat();

117

pAnimal->Reproduce();

118

pAnimal->Move();

119

pAnimal->Sleep();

120
121

delete pAnimal;
cout << "\ n";

122
123
124

}
return 0;
}

v (1)Dog (2)Horse (3)Bird (O)Quit: 1


Animal constructor...
Mammal constructor...
Dog constructor...
Woof!...
Dog eating.. .
Dog reproducing....
Dog running...
Dog snoring.. .
Dog destructor...
Mammal destructor...
Animal destructor...
(1)Dog (2)Horse (3)Bird (O)Quit: 0

721 Animal.
, ,
itsAge.
SleepO, Eat(), ReproduceO, Move() Speak() .
Mammal Animal 2937
. ReproduceO, ,
. Fish
Animal, ReproduceO , Mammal (
).
, Mammal,
ReproduceO,
, , , 83
Dog. Fish,
Horse Dog, .

13.

407

Animal,
. ,
, .
Animal
Mammal .


, , Animal

, .
?

, .
,
, . ,
, Animal
, Dog.
, Dog
, ,
. ,
.



.

.
,
,
.


C++
.
,
.
.
, Timer, .
- itsSeconds, ,
itsSeconds.
,
itsSeconds. , ,
Timer -.
,
.

408


,
,
.
,
Observer Update().
Subject.
Observer. , :
RegisterO, Observer, NotifyO,
.
.
, ,
Observer. Timer Subject.
( itsSeconds)
NotifyO, Subject.
, ObserverTimer,
Observer Timer,
.

,
Java
, Java C++.
, Java
, , ,
,
Java. Java, 90% ,
, .
Java
, , ,
.
.
, . ,
,
, . ,
, -,
.
,
. ,
C++,

, Java ( ).
C++ Java
: Robert Martin, C++ and Java: A Critical Comparison // C++
Report. January, 1997.

13.

409



.-

.
, , ,
.

.

.

-
. ,
.

?
,
, ,
. ,
,
.
, .

?

.
,
,
.

?
,
, ++.
, ++
,
,
, ++.

?
,
.
,
, .

410

?
, |

. :
, . >-

?
, ?
,
,
. ,
.


,
.
, .
,
.


1. ?
2. v-ptr?
3.

,
RoundRect, Rectangle Circle,
, , Shape.
Shape RoundRect?

4.

Horse Bird Animal ,


Animal?
Pegasus , Horse Bird,
Animal?

5. Vehicle () .
6.

ADT
, ,
?

1. JetPlane ( ),
Rocket () Airplane ().
2. JetPlane, , 747.

13.

411

3.

()

4.

,
ADT, : SportsCar (
), Wagon () Coupe ( -).
, Vehicle,
.

412

, ( ) Bus
Vehicle (). Vehicle
. Bus
.


C++
.
, ,
, . ,
- . :

- -

- -

-
,
, ,
. , Cat,
, ..
.

. ,
. - .
,
, , , , .
, , .
,
. 14.1 Cat
HowManyCats. Cat,
HowManyCats
.

14.

413

14.1. -
1:// 14.1. -
2:

3:
4:

include <iostream.h>

5:

class Cat

6:
{
7:
public:
8:Cat(int age):itsAge(age){ HowManyCats++; }
9:

virtual "Cat() { HowManyCats--; }

10: virtual int GetAgeO { return itsAge; }


11:virtual void SetAge(int age) { itsAge = age; }
12:

static int HowManyCats;

13:
14:

private:

15:

int itsAge;

16:
17:

} ;

18;
19:

int Cat::HowManyCats = 0;

20:
21:

int main()

22:
23:

{
const int MaxCats = 5; int i;

24:

Cat *CatHouse[MaxCats];

25:

for (i = 0; KMaxCats; i++)

26:

CatHouse[i] = new Cat(i);

27:
28:

for (i = 0; KMaxCats; i++)

29;

30:

cout "There are ";

31:

cout << Cat::HowManyCats;

32:
cout << " cats left!\ n";
33: cout << "Deleting the one which is .";
34:

cout CatHouse[i]->GetAge();

35:

cout << " years old\ n";

36:
37:

delete CatHouse[i];
CatHouse[i] = 0;

38:

39:

return 0; ,

40:

There are 5 cats left!


Deleting the one which is 0 years old
There are 4 cats left!
Deleting the one which is 1 years old
There are 3 cats left!
Deleting the one which is 2 years old

414

There are 2 cats left!


Deleting the one which is 3 years old
There are 1 cats left!
Deleting the one which is 4 years old

Cat 517.
static 12 -
HowManyCats int.
HowManyCats
, ..
, , ,
- Cat.
HowManyCats 19.
- (
).
:
undefined symbol Cat::HowManyCats

, - itsAge
, -
Cat, , , 26.
Cat, 8,
- . , 9,
1. , HowManyCats
Cat.
2140 Cat,
. Cat,
HowManyCats,
0.
for Cat ,
HowManyCats.
5 ( ) .
: HowManyCats public
main(). -
.
Cat, - . ,
Cat,
, 14.2,
-. .

14.2.
// 14.2. -

include <iostream.h>
class Cat

{
public:

14.

415

8: Cat(int age):itsAge(age){ HowManyCats++; }


9: virtual Cat() { HowManyCats--; }
10: virtual int GetAgeO { return itsAge; }
11: virtual void SetAge(int age) {itsAge = age;}
12: static int HowManyCats;
13:
14: private:
15; int itsAge;
16;
17: } ;
18;
19; int Cat::HowManyCats = 0;

20:
21: void TelepathicFunction();

22:
23: int main()
24: {
25: const int MaxCats = 5; int i;
26; Cat *CatHouse[MaxCats];
27:
28:
29:
30;

for (i = 0; KMaxCats; i++)


{
CatHouse[i] = new Cat(i);
TelepathicFunction();

31: }
32:
33: for ( i = 0; KMaxCats; i++)
34; {
35: delete CatHouse[i];
36: TelepathicFunction();
37; }
38: return 0;
39: }
40:
41: void TelepathicFunction()
42: {
43: cout << "There are ";
44: cout << Cat::HowManyCats << " cats alive!\ n";
45: }

There

are 1 cats alive!

There

are 2 cats alive!

There are 3 cats alive!


There are 4 cats alive!
There are 5 cats alive!
There

are 4 cats alive!

There are 3 cats alive!


There are 2 cats alive!
There are 1 cats alive!
There are 0 cats alive!

416

* 14.2 14.1,
' TelepahicFunction(). Cat
, - HowManyCats.
, -
- , .
public, .
- ,
-.
. 14.3.
-.
*

14.3. -
// 14.3. -

include ciostream.h>
class Cat

{
public:
Cat(int age):itsAge(age){ HowManyCats++; }
virtual "Cat() { HowManyCats--; }
virtual int GetAge() { return itsAge; }
virtual void SetAge(int age) { itsAge = age; }
virtual int GetHowMany() { return HowManyCats; }

private:
int itsAge;
static int HowManyCats;

);
int Cat::HowManyCats = 0;
int main()

{
const int MaxCats = 5; int i;
Cat *CatHouse[MaxCats];
for (i = 0; i<MaxCats; i++)
CatHouse[i] = new Cat(i);
for (i = 0; KMaxCats; i++)

{
cout << "There are ";
cout << CatHouse[i]->GetHowMany();
cout << " cats left!\ n";
cout << "Deleting the one which is
cout << CatHouse[i]->GetAge()+2;
cout << " years old\ n";
delete CatHouse[i];

14.

417

38: CatHouse[i] = 0;
39: }
40: return 0;
41: }

There are 5 cats

left!

Deleting the one

which

is 2 years old

There are 4 cats


left!
Deleting the one which
is 3 years old
There are 3 cats

left!

Deleting the one which


There are 2 cats

is 4 years old

left!

Deleting the one which

is 5 years old

There are 1 cats


left!
Deleting the one which
is 6 years old

17 - HowManyCats private.
,
, TelepathicFunction .
HowManyCats ,
. , GetHoqMany(),
, -.
GetHowManyO , .


.

-, private
protected.

-
.

.

-
- -:
, .
,
, 14.4.

14.4. -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: // 14.4. -
2:

3: include ciostream.h>
4:
5: class Cat

418

:2

6: {
7: public:
8: Cat(int age):itsAge(age){ HowManyCats++; }
9: virtual Cat() { HowManyCats--; >
10: virtual int GetAgeO { return itsAge; }
11: virtual void SetAge(int age) { itsAge = age; }
12: static int GetHowManyO { return HowManyCats; }
13: private:
14: int itsAge;
15: static int HowManyCats;
16: } ;
17:
18: int Cat::HowManyCats = 0;
19:
20: void TelepathicFunction();

21:
22: int main()
23: {
24: const int MaxCats = 5;
25: Cat *CatHouse[MaxCats]; int i;
26: for (i = 0; i<MaxCats; i++)
27: {
28: CatHouse[i] = new Cat(i);
29: TelepathicFunction();
30: }
31:
32: for ( i = 0; KMaxCats; i++).
33: {
34: delete CatHouse[i];
35: TelepathicFunction();
36: }
37: return 0;
38: }
39:
40: void TelepathicFunction()

41: {
42:

cout

<<

"There

are

"

<<

Cat::GetHowMany()

"

cats

alive!\

n"

43: >

There are 1 cats alive!


There are 2 cats alive!
There

are 3 cats alive!

There are 4 cats alive!


There are 5 cats alive!
There are 4 cats alive!
There are 3 cats alive!
There

are 2 cats alive!

There are 1 cats alive!


There are 0 cats alive!

14.

.419

. ' -
15 Cat * . - HowManyCats. 12
- GetHowManyO GetHowManyO ,
,
Cat. TelepathicFunctionO 42
GetHowManyO, Cat. , GetHowManyO
main , Cat.

- this.
const. ,
- -
this, -
-!

-
- ,
-, ,
.
:

static int GetHowManyO {. return; HowManyCats; }

^MsltaliJJint^llowMahyCSlST^

.
911
..
:

'' ..Cat theCat; - // on |


howMany = theCat.GetHowManyO; //
);;/ // '.'


, ,
. -
.
, ,
, .

, . int
.
.

420


long (* funcPtr) (int);

funcPtr ( *
),
long. (* funcPtr) ,
(int)
(*). , funcPtr,

long. (, C++ .)
:
long * Function (int);
long (* funcPtr) (int);

FunctionO ,
long. funcPtr
,
long.

, .
14.5.

14.5. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1;// 14.5.

2;
3;

include <iostream.h>

4;
5;
6;

void Square (int&,int&);


void Cube (int&, int&);

7:

void Swap (int&, int &);

8;
9;

void GetVals(int&, int&);


void PrintVals(int, int);

10;
11;

int main()

12;

13;
14;

void (* pFunc) (int &, int &);


bool fQuit = false;

15:
16:

int val0ne=1, valTwo=2;

17:

int choice;

18:
19:

while (fQuit == false)


{

20:cout "(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap";


21:
22:

ein choice;
switch (choice)

23:
24:

{
case 1: pFunc = GetVals; break;

25:

case 2: pFunc = Square; break;

26:
27:

case 3: pFunc = Cube; break;


case 4: pFunc = Swap; break;

28:

default : fQuit = true; break;

14.

421

29: }
30:
31:
32:
33:
34:
35:
36:
37:
38:

if (fQuit)
break;
PrintVals(valOne, valTwo);
pFunc(valOne, valTwo);
PrintVals(valOne, valTwo);
}
return 0;

39: }
40:
41: void PrintVals(int x, int y)
42: {
43: cout << "x: " << x " y: " << y << endl;
44: }
45:
46:
47:
48:
49:

void Square (int & rX, int & rY)


{
rX *= rX;
rY *= rY;

50: }
51:
52: void Cube (int & rX, int & rY)
53: {
54: int tmp;
55:
56: tmp = rX;
57: rX *= rX;
58: rX = rX * tmp;

59:
60: tmp = rY;
61: rY *= rY;
62: rY = rY * tmp;
63: >
64;
65: void Swap(int & rX, int & rY)

66: {
67: int temp;
68: temp = rX;
69: rX = rY;
70: rY = temp;
71: }

72:
73: void GetVals (int & rValOne, int & rValTwo)
74: {
75: cout << "New value for ValOne: ";
76: cin >> rValOne;
77: cout << "New value for ValTwo: ";
78: cin >> rValTwo;
79: }

422

(O)Ouit (1)Change Values (2)Square (3)Cube (4)Swap: 1


x: 1 y: 2
New value for ValOne: 2
New value for ValTwo: 3
x: 2 y: 3
(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 3
x: 2 y: 3
x: 8 y: 27
(O)Qult (1)Change Values (2)Square (3)Cube (4)Swap: 2
x: 8 y: 27
x: 64 y: 729
(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 4
x: 64 : 729
x: 729 : 64
(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 0

58
. void
int.
13 pFunc ,
int void.
. ,
pFunc. 3436
,
.


,
, .
.
,
- . , ,
.
, .
, .
:

1:0^>'!'*'' , ! : ! ;


, 14.5,
,
: .
14.6 14.5,
. .

14.

423

14.. 14.S
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1:// 14,6. 14,5
//
2:
3:

include <lostream.h>

4:
5:

void Square (int&,int&) ;

6:

void Cube (int&, int&);

7:

void Swap (int&, int &);

8:

void GetVals(int&, int&);

9:

void PrintValsCint, int);

10 :
11:

int main()

12:

13:

bool fQuit = false;

14:

int valOne=1, valTwo=2;

15:
16:

int choice;
while (fQuit == false)

17:
{
18:cout "(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap";
19:

cin >> choice;

20:

switch (choice)

21:

22:

case 1:

23:

PrintVals(valOne, valTwo);

24:

GetVals(valOne, valTwo);

25:

PrintVals(valOne, valTwo);

26:

break;

27:
28:
29:
30:

case 2:
PrintVals(valOne, valTwo);
Square(valOne,valTwo);

31:

PrintVals(valOne, valTwo);

32:

break;

33:
34:

case 3:

35:

PrintVals(valOne, valTwo);

36;

Cube(valOne, valTwo);

37:

PrintVals(valOne, valTwo);

38:

break;

39:
40:
41:

case 4:
PrintVals(valOne, valTwo);

42:
43:

Swap(valOne, valTwo);
PrintVals(valOne, valTwo);

44:

break;

45:
46:

424

default :

47:

fOuit = true;

48:

break;

49: }
50:
51: if (fOuit)
52:

break;

53: }
54: return 0;
55: }
56:
57: void PrintVals(int x, int y)
58; {
59: cout << "x: " << x << " y: " << y << endl;

60: }
61:
62: void Square (int & rX, int & rY)
63: {
64: rX *= rX;
65: rY *= rY;

66: }
67:
68: void Cube (int & rX, int & rY)
69: {
70: int tmp;
71:
72: tmp = rX;
73: rX *= rX;
74: rX = rX * tmp;
75:
76: tmp = rY;
77: rY *= rY;
78: rY = rY * tmp;
79: >
80:
81: void Swap(int & rX, int & rY)
82: {
83: int temp;
84: temp = rX;
85: rX = rY;
86: rY = temp;
87: }

88:
89: void GetVals (int & rValOne, int & rValTwo)
90: {
91: cout "New value for ValOne:
92: cin rValOne;
93: cout "New value for ValTwo: ";
94: cin rValTwo;
95: }

14.

425

t \ (O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 1


ifatosiiilii x: 1 y: 2
New value for ValOne: 2
New value for ValTwo: 3
(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 3
x: 2 : 3
x: 8 y: 27
(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 2
x: 8 y: 27
x: 64 y: 729
(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 4
x: 64 : 729
x: 729 y: 64
(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 0

, 14.5. ,
, .
22 46 . , PrintVals()
case.
PrintValsO
while, case.
PrintVals() , .
.....


,
. , , pFunc ,
long,
pFunc. :

' Futve,)i{ :) 4 ;

.
, .

. ,
.
,
.
,
.



,
. 14.7 14.5,
.

426

14.7.
1:

//

14.7.

2:

3: include <iostream.h>
4:
5: void Square (int&,int&);
6: void Cube (int&, int&);
7: void Swap (int&, int &);
8: void GetVals(int&, int&);
9: void PrintVals(int, int);

10:
11: int main()

12:

13: int valOne=1, valTwo=2;


14: int choice, i;
15: const MaxArray = 5;
16: void (*pFuncArray[MaxArray])(int&, int&);
17:
18: for (i=0;i<MaxArray;i++)
19: {
20: cout << "(1)Change Values (2)Square (3)Cube (4)Swap: ";
21: cin >> choice;
22: switch (choice)
23: (
24:
case 1:pFuncArray[i] = GetVals; break;
25:

case 2:pFuncArray[i] = Square; break;

26:
27:

case 3:pFuncArray[i] = Cube; break;


case 4:pFuncArray[i] = Swap; break;

28:

default:pFuncArray[i] = 0;

29: }
30: }
31:
32: for (i=0;i<MaxArray; i++)
33: {
34: if ( pFuncArray[i] == 0 )
35:
continue;
36: pFuncArray[i](valOne,valTwo);
37: PrintVals(valOne,valTwo);
38: }
39: return 0;
40: }
41:
42; void PrintVals(int x, int y)
43: {
44: cout "x: " << x << " y: " << << endl;
45: }
46:
47: void Square (int & rX, int & rY)
48: <
49: rX *= rX;

14.

50: rY *= rY;

51: }
52:
53: void Cube (int & rX, int & rY)
54: {
55: int tmp;
56:
57: tmp = rX;
58: rX *= rX;
59: rX = rX * tmp;
60:
61: tmp = rY;
62: rY *= rY;
63: rY = rY * tmp;
64: }
65:
66: void Swap(int & rX, int & rY)
67: {
68:
69:
70:
71:

int temp;
temp = rX;
rX = rY;
rY = temp;

72: }
73:
74: void GetVals (int & rValOne, int & rValTwo)
75: {
76: cout "New value for ValOne: ";
77: cin >> rValOne;
78: cout "New value for ValTwo: ";
79: cin rValTwo;
80: >

(1)Change Values (2)Square (3)Cube (4)Swap: 1


(1)Change Values (2)Square (3)Cube (4)Swap: 2
(1)Change Values (2)Square (3)Cube (4)Swap: 3
(1)Change Values (2)Square (3)Cube (4)Swap: 4
(1)Change Values (2)Square (3)Cube (4)Swap: 2
New Value for ValOne: 2
New Value for ValTwo: 3
x: 2 y: 3
x: 4 y: 9
x: 64 y: 729
x: 729 y: 64
x: 531441 :4096

,
,
, 14.5. 16 pFuncArray,
, void
int.

428

18-30
. .
32-38,
.


( )
.
14.5 ,
( main()), ,
.
14.8.

14.8. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1:// 14.8.
2:

3:
4:

include <iostream.h>

5:
6:

void Square (int&,int&);


void Cube (int&, int&);

7:

void Swap (int&, int &);

8:

void GetVals(int&, int&);

9:void PrintVals(void (*)(int&, int&),int&, int&);


10 :
11:

int main()

12:

13:

int val0ne=1, valTwo=2;

14:

int choice;

15:

bool fQuit = false;

16:
17:
18:

void (*pFunc)(int&, int&);

19:

while (fQuit == false)

20:

21:cout << "(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: ";


22:
cin >> choice;
23:

switch (choice)

24:

25:

case 1:pFunc = GetVals; break;

26:

case 2:pFunc = Square; break;

27:

case 3:pFunc = Cube; break;

28:

case 4:pFunc = Swap; break;

29:

default:fQuit = true; break;

30:

31:
32:

if (fQuit == true)
break;

33:

PrintVals ( pFunc, valOne, valTwo);

34:

35:

14.

429

36: return 0;
37: }
38:
39: void PrintVals( void (*pFunc)(int&, int&),int& x, int& y)
40: {
41: cout << "x: " << x << " y: " y << endl;
42: pFunc(x,y);
43: cout << "x: " << x << " y: " y << endl;
44: }
45:
46: void Square (int & rX, int & rY)
47: {
48: rX *= rX;
49: rY *= rY;
50: }
51:
52: void Cube (int & rX, int & rY)
53: {
54: int tmp;
55:
56: tmp = rX;
57: rX *= rX;
58: rX = rX * tmp;
59:
60: tmp = rY;
61: rY *= rY;
62: rY = rY * tmp;
63: }
64:
65: void Swap(int & rX, int & -rY)

66: {
67: int temp;
68: temp = rX;
69: rX = rY;
70: rY = temp;
71: }

72:
73: void GetVals (int & rValOne, int & rValTwo)
74: {
75: cout << "New value for ValOne: ";
76: cin >> rValOne;
77: cout << "New value for ValTwo: ";
78: cin >> rValTwo;
79: }

PESVJIkTAT

(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 1


x: 1 y: 2
New value for ValOne: 2
New value for ValTwo: 3

430

Heenn2

fJTl x: 2 y: 3

iSMS (O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 3


x: 2 y: 3
x: 8 y: 27
(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 2
x: 8 y: 27
x: 64 : 729
(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 4
x: 64 : 729
x: 729 :64
(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 0

17 pFunc,
int void. PrintVals,
, 9.
, void int.
PrintVals
int. , 33
PrintVals.
, C++,
:

void PrintVals(void (*)(int&, int&), int&, int&);

,
, .
,
.

tgpedef |
void (*)(int&, int&) .
typedef, ( VPF)
, void
int. 14.9 14.8
.

14.8. typedef

14.9.

//

//

typedef

include <iostream.h>
void Square (int&,int&);
void Cube (int&, int&);
void Swap (int&, int &);
void GetVals(int&, int&);
9:
10:

typedef
void

void

(*VPF)

(int&,

PrintVals(VPF,int&,

int&)
int&);

11:

14:

12; int main()


13: {
14: int valOne=1, valTwo=2;
15: int choice;
16: bool fQuit = false;
17:
18: VPF pFunc;
19:
20: while (fQuit == false)

21: {
22: cout << "(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap:
23: cin choice;.
24: switch (choice)
25: {
26: case 1:pFunc = GetVals; break;
27: case 2:pFunc = Square; break;
28: case 3:pFunc = Cube; break;
29: case 4:pFunc = Swap; break;
30: default:fQuit = true; break;
31:
32:

}
if (fQuit == true)

33:

break;

34:

PrintVals ( pFunc, valOne, valTwo);

35:

36:

return 0;

37:

38:
39:

void PrintVals( VPF pFunc,int& x, int& y)

40:

41:

cout "x: " x " y; " y endl;

42:
43:

pFunc(x.y);
cout "x: " x " y: " << y endl;

44:

45:
46:
47:

void Square (int & rX, int & rY)


{

48: rX *= rX;
49: rY *= rY;
50:

51:
52:

void Cube (int & rX, int & rY)

53:

54: int tmp;


55:
56: tmp = rX;
57: rX *= rX;
58: rX = rX * tmp;
59:
60: tmp = rY;
61: rY *= rY;

432

62: rY = rY * tmp;
63: }
64:
65: void Swap(int & rX, int & rY)
66: {
67: int temp;
68: temp = rX;
69: rX = rY;
70: rY = temp;
71: >
72:
73: void GetVals (int & rValOne, int & rValTwo)
74: {
75: cout << "New value for ValOne: ";
76: cin >> rValOne;
77: cout << "New value for ValTwo: ";
78: cin >> rValTwo;
79: }

' "

(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 1


x: 1 y: 2
New value for ValOne: 2
New value for ValTwo: 3

x: 2 y: 3
(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 3
x: 2 : 3
x: 8 y: 27
(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 2
x: 8 y: 27
x: 64 : 729
(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 4
x: 64 y: 729
x: 729 y: 64
(O)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 0

9 typedef VPF
, void int.
10 PrintVals(), : VPF
integer. 18 Pfunc VPF.
VPF pFunc
PrintValsO . ,
, .

-

, - .
, ().

14.

433

,
, (::
, pFunc - Shape,
void, :
void (Shape::*pFunc) (int.int);

- ,
. ,
,
. 14.10 .

14.10. -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: // 14.10. -
2:

3:
4:

include <iostream.h>

5:

class Mammal

6:

7:
8:
9:
10:
11:
12:

public:
Mammal():itsAge(1) { }
virtual ~Mammal() { }
virtual void Speak() const = 0;
virtual void Move() const = 0;
protected:

13:

int itsAge;

14:
15:

} ;

16:
17:
18:

class Dog : public Mammal


{
public:

19:

void Speak()const { cout << "Woof!\ n"; }

20:void Move() const { cout << "Walking to heel...\ n"; }

21:

};

22:
23:
24:
25:
26:

class Cat : public Mammal


{
public:

27:
28:

void Speak()const { cout << "Meow!\ n"; }


void Move() const { cout << "slinking...\ n"; }

29:
30:

} ;

31:
32:
33:
34:

class Horse : public Mammal


{
public:

35:
36:
37:

void Speak()const { cout "Whinny!\ n"; }


void Move() const { cout << "Galloping..,\ n"; }
} ;

38:
39:

434

40:

int main()

41:

42:

void (Mammal::*pFunc)() const =0;

43:
44:

Mammal* ptr =0;


int Animal;

45:

int Method;

46:
47;

bool fQuit = false;

48:
49:

while (fQuit == false)


{

50:
51:

cout << "(O)Quit (1)dog (2)cat (3)horse


cin >> Animal;

52:

switch (Animal)

53:

54:

case 1: ptr = new Dog; break;

55:

case 2: ptr = new Cat; break;

56:
57:
58:
59:
60:

case 3: ptr = new Horse; break;


default: fQuit = true; break;
}
if (fQuit)
break;

61:
62:

cout << "(1)Speak (2)Move:

63:
64:

cin >> Method;


switch (Method)

65:
66:
67:

{
case 1: pFunc = Mammal::Speak; break;
default: pFunc = Mammal::Move; break;

68:

69:
70:
71:
72:
73:
74:

(ptr->*pFunc)();
delete ptr;
}
return 0;
}

I";
(0)Quit (1)dog (2)cat (3)horse: 1
Mi! run ftiff (i)Speak (2)Move: 1
Woof!
(0)Quit
(1)Speak

(1)dog (2)cat (3)horse: 2


(2)Move: 1

Meow!
(0)Quit
(1)Speak

(1)dog (2)cat (3)horse: 3


(2)Move: 2

Galloping
(0)Quit (1)dog (2)cat (3)horse: 0

414 Mammal ^'


Speak() Move(). Mammal
Dog, Cat Horse,
Speak() Move().

14.

435

main()
,
, 5456 ptr.
, pFunc.
70
ptr pFunc.
, 71 ptr delete,
, . ,
delete pFunc, ,
.
.

-
, -
.
-. ,
, .
14.11.

14.11. -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1:

// 14.11. -

2:

3:

ffinclude <iostream,h>

4:
5:

class Dog

6:

<

7:

public:

8:

void SpeakQconst { cout << "Woof!\ n"; }

9:

void Move() const { cout << "Walking to heel...\ n"; }

10:

void Eat() const { cout << "Gobbling food...\ n"; }

11:

void Growl() const { cout << "Grrrrr\ n"; }

12:

void WhimperO const { cout << "Whining noises...\ n"; }

13:

void RollOverO const { cout << "Rolling over...\ n"; }

14:void PlayDeadO const { cout << "Is this the end of Little Caesar?\ n"; }
15:

> ;

16:
17:

typedef void (Dog::*PDF)()const ;

18:

int main()

19:

20:

const int MaxFuncs = 7;

21:

PDF DogFunctions[MaxFuncs] =

22:

{ Dog::Speak,

23:

Dog::Move,

24:

Dog::Eat,

25:

Dog::Growl,

26:

Dog::Whimper,

27:

Dog::Roll0ver,

28:

Dog::PlayDead } ;

436

29:
30: Dog* pDog =0;
31: int Method;
32: bool fQuit = false;
33:
34: while (!fQuit)
35: {
36:
37:

cout
cout

<<

"(O)Quit
"

(1)Speak

(5)Whimper

(6)Rol1

(2)Move
Over

(3)Eat
(7)Play

(4)Growl";
Dead:

";

38: cin >> Method;


39: if (Method == 0)
40: {
41:

fQuit = true;

42: }
43: else
44: {
45:

pDog = new Dog;

46:

(pDog->*DogFunctions[Method-1 ])();

47:

delete pDog;

48: >
49: }
50: return 0;
51: }

(0)Quit (1)Speak (2)Move (3)Eat (4)Growl (5)Whimper (6)Rol1 Over (7)Play


Dead: 1
Woof!
(0)Quit (1)Speak (2)Move (3)Eat (4)Growl (5)Whimper (6)Roll Over (7)Play
Dead: 4
Grrr
(0)Quit (1)Speak (2)Move (3)Eat (4)Growl (5)Whimper (6)Roll Over (7)Play
Dead: 7
Is this the end of Little Caesar?
(0)Quit (1)Speak (2)Move (3)Eat (4)Growl (5)Whimper (6)Roll Over (7)Play
Dead: 0

.,

515 Dog, -,
.
17 typedef PDF -
Dog, .
2128 DogFunctions,
-.
36 37 .
, Quit, Dog,
( 46). ,
, C++:
(pDog->*-Dog Functions[Method-1 ])();

, , ,
-, .

14.

437


.
^
-.


-,
.

- ,
, -, ,
. - public,
, ,
.
-
. ,
,
-.
,
-.
- ,
-. -
, .
-.
- this,
-.
- this -
const. , - const
, this .
, ,
-,
.
, -
,
.
.


, ?
.
- ,
, ( , -
public), - .
- ,

438

. ,
++, -
.

-,
?
-
, :
1:: 1().


-?
. .
.


,
.
, .
,
.

1. - ?
2. -.
3. .

4.

, int
long.

5. , 4, - .
6. , 5.

1.

, - -. ,
-
-. ,
.

2.

1,
, ,
- - .
-.

14.

439

3.

2 ,
- -.
- .

4. 3 -
-
.
5.

- .
, .
-
. -.

440


,
,
.
, ,
, , , ,
, , ,
. ,
. ++
.
.
,
.
,
.
311 .
, , .

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

//
II * * * *

2.

441

18:
19: include <iostream.h>
20:
21:
22:

23: f f **************** ***********'*


24:
25: // ,
26: class Part
27: {
2: public:
29:

rt():itsPartNumber(1) { }

30:

Part(int PartNumber):itsPartNumber(PartNumber){ }

31:

virtual "Part(){ } ;

32:

int GetPartNumber() const { return itsPartNumber; }

33:

virtual void DisplayO const =0: // private

34: private:
35:

int itsPartNumber;

36: > ;
37:
38: //
39: //
40: void Part::Display() const
41: {
42:

cout << "\ : " << itsPartNumber endl;

43: }
44:
45: // ************* **********
46:
47: class CarPart : public Part
48: {
49: public:
50:

CarPartO : itsModelYear(94) { }

51:

CarPart(int year, int partNumber);

52:
53:

virtual void DisplayO const


{

54:
55:
56:

Part::DisplayO; cout " : ";


cout << itsModelYear << endl;
}

57: private:
58:

int itsModelYear;

59: } ;
60:
61: CarPart::CarPart(int year, int partNumber):
62:
63:

itsModelYear(year),
Part(partNumber)

64: { }
65:
66:
67; // ************* **********

442

68:
69: class AirPlanePart : public Part
70: {
71: public:
72:

AirPlanePart():itsEngineNumber(1) { } ;

73:

AirPlanePart(int EngineNumber, int PartNumber);

74:
75:

virtual void DisplayO const


{

76:

Part::Display(); cout << " :

77:

cout << itsEngineNumber << endl;

78:

79: private:
80:

int itsEngineNumber;

81: } ;
82:
83: AirPlanePart::AirPlanePart(int EngineNumber, int PartNumber):
84:

itsEngineNumber(EngineNumber),

85:

Part(PartNumber)

86 : { }

87:
88: // ************** **********
89: class PartNode
90: {
91: public:
92:

PartNode (Part*);

93:

"PartNodeO;

94:

void SetNext(PartNode * node) { itsNext = node; }

95:

PartNode * GetNextO const;

96:

Part * GetPart() const;

97: private:
98:

Part *itsPart;

99:
100: } ;

PartNode * itsNext;

101 :

102: // PartNode...
103:
104: PartNode::PartNode(Part* pPart):
105: itsPart(pPart),
106: itsNext(O)
107: { }
108:
109: PartNode::'PartNode()

110: {
111:

delete itsPart;

112:

itsPart = 0;

113:

delete itsNext;

114:

itsNext = 0;

115: }
116:
117: // NULL, PartNode

2.

118: PartNode * PartNode::GetNext() const


119: {
120:

return itsNext;

121: }

122:
123: Part * PartNode::GetPart() const
124: {
125:
126:

if (itsPart)
return itsPart;

127:

else

128:

return NULL; //

129: }
130:
131: // **************** *.****.***
132: class PartsList
133: <
134: public:
135:
136:
137:

PartsList();
//

-PartsListO;
,

138:

139:

int GetCountO const { return itsCount; }

140:

Part* GetFirstO const;

141:
142:

static PartsList& GetGlobalPartsList()


{

143:
144:

Part* Find(int & position, int PartNumber) const;

return GlobalPartsList;
}

145:

void

146:

void

147:

Insert(Part *);
Iterate(void (Part::*f)()const) const;

Part* operator[](int) const;

148: private:
149:

PartNode * pHead;

150:
151:

int itsCount;
static PartsList GlobalPartsList;

152: } ;
153:
154: PartsList PartsList::GlobalPartsList;
155:
156: // ,,.
157:
158: PartsList::PartsList():
159:

pHead(O),

160:

itsCount(O)

161: { }
162:
163: PartsList::"PartsList()
164: {
165:

delete pHead;

166: }
167:

444

168: Part* PartsList::GetFirst() const


169: {
170:

if (pHead)

171:
172:

return pHead->GetPart();
else

173:

return NULL; //

174: }
175:
176: Part * PartsList::operator[](int offSet) const
177: {
178:

PartNode* pNode = pHead;

179:
180:

if (!pHead)

181:

return NULL; //

182:
183:

if (offSet > itsCount)

184:

return NULL; //

185:
186:

for (int i=0;i<offSet; i++)

187:
188:
189:

pNode = pNode->GetNext();
return pNode->GetPart();

190: }
191:
192: Part* PartsList::Find(int & position, int PartNumber) const
193: {
194:

PartNode * pNode = 0;

195:

for (pNode = pHead, position = 0;

196:

pNode!=NULL;

197:

pNode = pNode->GetNext(), position++)

198:
199:

{
if (pNode->GetPart()->GetPartNumber() == PartNumber)

200:

break;

201: }
202;

if (pNode == NULL)

203:
204:

return NULL;
else

205:

return pNode->GetPart();

206: >
207:
208: void PartsList::Iterate(void (Part::*func)()const) const
209: {
210:

if (!pHead)

211:

return;

212:

PartNode* pNode = pHead;

213:

do

214:
215:

(pNode->GetPart()->*func)();
while (pNode = pNode->GetNext());

216: }
217:

2.

218:

void PartsList::Insert(Part* pPart)

219:

<

220 :
221:

PartNode * pNode = new PartNode(pPart);

222:

PartNode * pNext = 0;

223:
224:

int New = pPart->GetPartNumber();

PartNode * pCurrent = pHead;

225:

int Next = 0;

226:
227:

itsCount++;

228:

if (!pHead)

229:

{
pHead = pNode;

230:

return;

231:
232:

233:
234:

// ,

235:

//
if (pHead->GetPart()->GetPartNumber() > New)

236:
237:
238:

{
pNode->SetNext(pHead);
pHead = pNode;

239:

return;

240:
241:

242:
243:

for (;;)

244:

245:

// ,

246:

if (!pCurrent->GetNext())

247:

<

248:

pCurrent->SetNext(pNode);
return;

249:
250:

>

251:
// , ,

252:

// . Next

253:
254:
255:

pNext = pCurrent->GetNext();
Next = pNext->GetPart()->GetPartNumber();

256:

if (Next > New)

257:

258:

pCurrent->SetNext(pNode);

259:

pNode->SetNext(pNext);
return;

260:
261:

262:

pCurrent = pNext;

263:
264:

>
}

265:
266:

int main()

267:

268:

Pa rtslist&pl = PartsList::GetGlobalPa rtsList();

269:

Part * pPart = 0;

270:

int PartNumber;

271:

int value;

272:

int Choice;

273:
274:

while (1)

275:
276:

277:

cout << "(O)Quit (1)Car (2)Plane: ";


cin >> choice;

278:
279:

if (Ichoice)

280:

break;

281:
282:

cout << "New PartNumber?: ";

283:

cin >> PartNumber;

284:
285:

if (choice == 1)

286: {
287:

cout << "Model Year?: ;

288:

cin >> value;

289:

pPart = new CarPart(value,PartNumber);

290:
291:

}
else

292:

293:

cout << "Engine Number?: ";

294:

cin >> value;

295:
296:

pPart = new AirPlanePart(value,PartNumber);


}

297:
298:
299:
300:
301:
302:

pi.Insert(pPart);
}
void (Part::*pFunc)()const = Part:: Display ;
pl.Iterate(pFunc);
return 0;

303: }

(0)Quit (1)Car (2)Plane: 1


New PartNumber?: 2837
Model Year? 90
(0)Quit (1)Car (2)Plane: 2
New PartNumber?: 378
Engine Number?: 4938
(0)Quit (1)Car (2)Plane: 1
New PartNumber?: 4499
Model Year? 94
(0)Quit (1)Car (2)Plane: 1
New PartNumber?: 3000
Model Year? 93

2.

447

(O)Quit (1)Car (2)Plane:


Part Number: 378
Engine No.: 4938
Part Number: 2837
Model Year: 90
Part Number: 3000
Model Year: 93
Part Number: 4499
Model Year: 94

Part.
,
,
.
Part, Part
,
- itsPartNumber. Part
CarPart AirPlanePart.
Part 2636, -
. ,

. Part ,
DisplayO.
, 4043
DisplayO. , DisplayO
,
.
, CarPart AirPlanePart,
4759 6987 . DisplayO
DisplayO .
PartNode Part rtList.
Part .

Part.
PartsList,
132152.
(pHead) , ,
.
, NULL.
, .

,
.
PartsList ,
. ,
.

448

Find() PartNumber int.


PartNumber,
Part . PartNumber
, NULL.
GetCountO
. PartsList - itsCount,
, .
GetFirstO Part
NULL, .
QetQlobalrtsList () -
GiobalPartsList. GlobaiPartsList
PartsList, , ,
.
Part ,
GiobalPartsList.
Insert Part,
PartNode Part PartNumber.
Iterate - Part
, void.
Part . Part
DisplayO, . ,
DisplayO, Part.
Operator[] Part
.
: , ,
NULL, .

.
main() 266-303. 268
PartsList GiobalPartsList.
, GiobalPartsList 154. ,
-
. -
.
274299 ,
. ,
, 298.
InsertO PartList 218264.
2837 CarPart,
Linked Li st: :Insert()c 90.
220 PartNode,
. New . - itsCount
PartsList 226.
228 pHead NULL.
TRUE, pHead
. 230 pHead
.
.
37 4938.

2.

449

PartsList:: Insert() pNode .


- itsCount 2 pHead.
pHead , .
236 , ,
pHead ( 2837), 378.
, 236 TRUE
.
238 pNode ,
pHead. ,
, , . 239 pHead
.
4499
94.
.
, pHead,
for 243.
378.
2837. 4499.
pCurrent . next
, pCurrent, .
, 246 False.
pCurrent , .
246 .
, .
3000.
,
2837, 4499. 256
TRUE, .

0, 279 TRUE
while(1) . 300 - DisplayQ
- pFunc.
, .
- Iterate PartsList. 208
Iterate() , . 213215
-
Part. Part
DisplayO, .

450


, ++ .
-
, .



. 16 , 17
++ .
18 - .
,
- . 19
, 20
. ,
++,
.


. :

, , , ,
, -
. C++ ,
. , Employee -
( )
( ..).
15.1 , String.
- ,
.

15.1. s t r i n g _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1:

include <iostream.h>

2:

include <string.h>

3:
4:

class String

5:
6:

<
public:

7:

//

8:

St ring();

9: String(const char *const);

452

10:

String(const String &);

11:

"StringO;

12:

13:

//

14:

char & operator[](int offset);

15:
16:

char operator[](int offset) const;


String operator+(const String&);

17:

void operator+=(const StringS);

18:

String & operator= (const String &);

19:
20:

//

21:

int GetLen()const { return itsLen; }

22: const char * GetStringO const { return itsString; }


23:// ConstructorCount;
24:
25:

private:

26:

String (int); //

27:

char * itsString;

28:
29:

unsigned short itsLen;

30:

} ;

31:
32:// String 0
33:
34:

String::St ing()
{

35:

itsString = new char[1];

36:

itsString[0] = '\ O;

37:

itsLen=0;

38:

// cout "\ tOefault string constructor\ n";

39:

// ConstructorCount++;

40:

41:
42:
43:

// ,
//

44:

// ,

45:

String:;String(int Ian)

46:

47:

itsString = new char[len+1]:

48;

for (int 1 = 0; i<=len; i++)

49;

itsString[i] * \ O';

50:

itsLen=len;

51:

// cout << "\ tString(int) constructor n";

52:

// ConstructorCount++;

53:

54:
55:

//

56:

String::St ing(const char * const cString)

57:

58:

itsLen = strlen(cString);

59:

itsString = new char[itsLen+1];

15.

60:

for (int i = 0; icitsLen; i++)

61:

itsString[i] = cSt ring[i ];

62:

itsString[itsLen]='\ O':

63: // cout << "\ tString(char*) constructor\ n";


64:

// ConstructorCount++;

65:

66:
67:

// -

68:

String::String (const String & rhs)

69:

70:

itsLen=rhs.Getlen();

71:

itsString = new char[itsLen+1];

72:

for (int i = 0; i<itsLen;i++)

73:

itsString[i] = rhs[i ];

74:

itsString[itslen] = '\ O;

75: // cout "\ tString(String&) constructor\ n";


76:
77:

// ConstructorCount++;
}

78:
79:

//

80:

String::"String ()

81:
82:
83:

{
delete [] itsString;
itsLen = 0;

84:

// cout "\ tString destructor\ n";

85:

86:
87: // ,
88:

//

89: Striflg& String::operator=(const String & rhs)


90:

91:
92:
93:

if (this == &rhs)
return this;
delete [] itsString;

94:

itsLen=rhs.GetLen();

95:

itsString = new char[itsLen+1];

96:

for (int i = 0; KitsLen; i++)

97:

itsString[i] = rhs[i ];

98:

itsString[itsLen] = \ O;

99:

return *this;

100:

// cout << "\ tString operator=\ n";

101:

102:

103: // ,
104:// ,
105:
106:
107:

//
char & String::operato[](int offset)
{

108:

if (offset > itslen)

109:

return itsString[itsLen-1];

454

110:

else

111:

return itsStnng[offset];

112 :

113:
114:

// ,

115:// (. -!)
116:

char String::operato[](int offset) const

117:

118:
119:

if (offset > itsLen)


return itsString[itsl_en-1 ];

120:

else

121:

return itsString[offset];

122:

123:
124:

// ,

125:

// rhs

126:

String String::operator+(const String& rhs)

127:

128:

int totalLen = itsLen + rhs.GetLen();

129:

String temp(totalLen);

130:
131:
132:

int i, j;
for (i = 0; i<itslen; i++)
temp[i] = itsString[i ];

133:

for (j = 0; j<rhs.GetLen(); j++, i++)

134:

temp[i] = rhs[j ];

135:
136:

temp[totalLen]=\ O';
return temp;

137:

138:
139: // ,
140:
141:

void String::operator+=(const String& rhs)


{

142:

unsigned short rhsLen = rhs.GetLen();

143:
144:

unsigned short totalLen = itsLen + rhsLen;


String temp(totalLen);

145:

int i, j;

146:

for (i = 0; KitsLen; i++)

147:

temp[i] = itsString[i];

148:

for (j = 0; j<rhs.GetLen(); j++, i++)

149:

temp[i] = rhs[i-itsLen ];

150:

temp[totalLen]='\ O;

151:

*this = temp;

152:

153:
154:

// int String::ConstructorCount = 0;

15.

455

15.1 String ,
12.12.
: 12.12
,
. 15.1 ,
.
- Const ructorCount
23 154.
String.
.
15.2 Employee, String.

15.2. E m p l o y e e _________________________________________________________
1:

include "String.hpp"

2:

3:

class Employee

4:

5;
6:

public:

7:
8:

EmployeeO;
Employee(char *, char *, char *, long);

9:

'EmployeeO;

10:

Employee(const Employee&);

11:

Employee & operator= (const Employee &);

12;
13;

const String & GetFirstName() const

14:

{ return itsFirstName; }

15;const String & GetLastName() const { return itslastName; }


16:const String & GetAddressO const { return itsAddress; }
17:

long GetSalaryO const { return itsSalary; }

18:
19;

void SetFirstName(const String & fNama)

20:

{ ItsFirstName = fName; }

21:

void SetLastName(const String & INama)

22:
23:

{ itsLastName = INamo; }
void SetAddress(const String & address)

24:

{ itsAddress = address; }

25:void SetSalary(long salary) { ItsSalary = salary; }


25:
27;

private:
String itsFirstName;

28;

String itslastName;

29:

String itsAddress;

30:

long ItsSalary;

31:
32:

} ;

33:

Employee:: EmployeeO :

34:

itsFirstNameC"),

35: itsLastNameC"),
36; itsAddressC"),

456

37:

itsSalary(O)

38:

{ }

39:
40:Employee::Employee(char * firstName, char * lastName,
41:

char * address, long salary):

42:
43:

itsFirstName(firstName),
itsLastName(lastName),

44:

itsAddress(address),

45:

itsSalary(salary)

46:
47:

{ >

48: Employee::Employee(const Employee & rhs):


49:

itsFirstName(rhs.Get FirstName()),

50:

itsLastName(rhs,Get LastName()),

51:

itsAddress(rhs.GetAddressO),

52:

itsSalary(rhs.GetSalaryO)

53:
54:

{ }

55:

Employee:;Employea() { }

56:
57:Employee & Employee::operator= (const Employee & rhs)
58:

59:
60:

if (this == &rhs)
return this;

61:
62:

itsFlrstName = rhs.GetFirstName();

63:

itsLastName = rhs.GetLastNameO;

64:

itsAddress = rhs,GetAddress();

65:

itsSalary = rhs.GetSala ry();

66:
67:

return this;

68:

69:
70:

int main()

71:
{
72:Employee Edie("Jane","Doe","1461 Shore Parkway", 20000);
73:
Edie.SetSalary(50000);
74:

String LastName("Levine");

75:

Edie.SetLastName(lastName);

76:

Edie.SetFirstName("Edythe");

77:
78:
cout << ": ";
79: cout Edie.GetFirstName().GetString();
80:cout << " " << Edie.GetLastName().GetString();
81:
82:

cout << ".\ : ";


cout Edie.GetAddress().GetString();

83:

cout << ",\ : " ;

84:
85:

cout Edie.GetSalaryO;
return 0;

86 :

15.

457

15.1 String.hpp.
, String,
15.1, include "String, hpp".
15.2.
Name: Edythe Levine.
Address: 1461 Shore Parkway.
Salary: 50000

15.2 Employee, -
String itsFirstName, itsLastName itsAddress.
72 Employee,
. 73 SetSalary Employee,
50000.
,
.
74
String, 75 SetLastName().
76 SetFirstName Employee
.
Employee, , SetFirstName(),
. SetFirstNameQ
String.
, 9 15.1 ,
String .


Employee String. Edie Employee
- itsLen, itsFirstName, .
. Employee
String, Employee
String, , - itsSalary .


, , , String operator+.
operator+ . ,
Employee , ,
GetFirstNameQ, . operator+
( ) ( , ),
:
Employee

String buffer = Edie.GetFirstName() + Edie.GetLastName();

458

GetFirstNameO
operator+ .
, GetFirstNameO
, :
const String & GetFirstNameO const { return itsFirstName; }
String & GetFirstNameO { return itsFirstName; }

, ,
-.
. .


,
Employee.
cout 15.1 ( 38, 51,
63, 75, 84 100), , . 15.3
, 15.2,
,
Employee.
.

38, 51, 63, 75, 84


100 15.1.

flucfflm 15.3. KoHcmppinopbi BAOieHHbix KnaccoB_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _


1:

include "String.hpp"

2:
3:

class Employee

4:
5:

6:

public:

7:

EmployeeO;

8:

Employee(char *, char *, char *, long);

9:

"EmployeeO;

10;

Employee(const Employee&);

11:

Employee & operator= (const Employee &);

12 ;
13:

const String & GetFirstNameO const

14:

{ return itsFirstName; }

15:const String & GetLastName() const { return itsLastName; }


16:const String & GetAddressO const { return itsAddress; }
17:
long GetSalaryO const { return itsSalary; }
18:
19:

void SetFirstName(const String & fName)

20:

{ itsFirstName = fName; }

15.

459

21:

void SetLastName(const String & IName)

22:

{ itslastName = IName; }

23:

void SetAddress(const String & address)

24:
{ itsAddress = address; }
25:void SetSalary(long salary) { itsSalary = salary; >
26:
27:

private:
String itsFirstName;

28:

String itsLastName;

29:

String itsAddress;

30:

long itsSalary;

31:
32:

} ;

33:

Employee::Employee():

34:

itsFirstName(""),

35;

itsLastNameC"),

36:

itsAddressC"),

37:

itsSalary(O)

38;

{ }

39:
40:Employee::Employee(char * firstName, char * lastName,
41:
char * address, long salary):
42:

itsFirstName(firstNama),

43;

itsLastName(lastName),

44;

itsAddrsss(address),

45;

itsSalary(salary)

46;

{ >

47:
48: Employee::Employee(const Employee & rhs):
49;

itsFi rstName(rhs,Get FirstName()),

50:

itsLastName(rhs.Get LastName()),

51:
52:

itsAddress(rhs.GetAddressO),
itsSalary(rhs.GetSalaryO)

53:
54:

{ }

55:

Employee::Employee() { }

56:
57;Employee & Employee::operator= (const Employee & rhs)
58:

59:

if (this == &rhs)

60:

return this;

61:
62:

itsFirstName = rhs.GetFi.rstName();

63;

itsLastName = rhs.GetLastNameO;

64:

itsAddress = rhs.GetAddress();

65:

itsSalary = rhs. GetSalaryO;

66:
67:

return this;

68:

69:
70;

460

int main()

71

{
cout "Creating Edie...\ n";

72
73

Employee Edie("Jane","Doe","1461 Shore Parkway", 20000);

74

Edie,SetSalary(20000);

75

cout "Calling SetFirstName with char n";

76

Edie. SetFirstNameCEdythe");

77

cout "Creating temporary string LastName,,,\ n";

78

String LastName("Levine");

79

Edie,SstLastName(LastName);

80
81

cout "Name;

82

cout Edie,QetFirstName(),Q@tString();

83

cout << " " << Edie,GetLastName().QetStrlng();

84

cout << "\ nAddress:

85

cout << Edie.GetAddress(),GetString();

86
87

oout << "\ nSalary: " ;


cout << Edie.GetSalary();

88
89
90

oout << endl;


return 0;
}

Creating Edie.,,
String(char*) constructor

String(char*) constructor

String(char*) constructor

Calling SetFirstName with char *...

String(char*) constructor

String destructor

Creating temporary string LastName,

String(char*) constructor

10 Name: Edythe Levine


11
12

Address: 1461 Shore Parkway


Salary: 20000

13

String

destructor

14

String

destructor

15

String

destructor

16

String destructor

15.3 ,
, cout .
, , , .
72 15.3 Creating Edie...,
. Edie Employee
.
String, .
75 SetFirstName.
, Edie.SetFirstName('Edythe"), String
"Edythe",

15.

461

String (. 6- ). ,
-,
String (. 7- ).
, .
,
String. ,
78 String. , ,
9- . ,
, .

Employee,
, Employee,
Last .


15.3 , Employee
String. 15.4
.
15.1 ( )
- ConstructorCount, String.
15.1, ConstructorCount
String.
, 15.4, Employee
, . - ConstructorCount ,
String Employee
.

15.1
, 15.3,
23, 39, 52, 64, 76 153.

15.4. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1:

include "String.hpp"

2:

3:

class Employee

4:

5:
6:

public:

7:

Employee();

8:

Employee(char *, char *, char *, long);

9;
10;
11:

"EmployeeO;
Employee(const Employee&);
Employee & operator= (const Employee &);

12:

13:

const String & GetFirstName() const

14:

{ return itsFirstName; }

15:const String & GetLastName() const { return itsLastName; }

462

16:const String & GetAddressQ const { return itsAddress;


17:

long GetSalaryO const { return itsSalary; }

18:

19:

void SetFirstName(const String & fName)

20:
21:

{ itsFirstName = fName; }
void SetLastName(const String & IName)

22:

{ itsLastName = IName; }

23:

void SetAddress(const String & address)

24:

{ itsAddress = address; >

25:void SetSalary(long salary) { itsSalary = salary; }


26:

private:

27:

String itsFirstName;

28:

String itsLastName;

29:

String itsAddress;

30:

long itsSalary;

31:

} ;

32:
33:

Employee::Employee():

34:

itsFirstName(""),
itsLastName(-'),

35:
36:

itsAddressO"),

37:

itsSalary(O)

38:
39:

{ }

40:Employee::Employee(char * firstName, char * lastName,


41:

char * address, long salary):

42:

itsFirstName(firstName),

43:

itsLastName(lastName),

44:

itsAddress(address),

45:

itsSalary(salary)

46:

{ }

47:
48:
49:
50:

Employee::Employee(const Employee & rhs):


itsFi rstName(rhs.GetFi rstName()),
itsLastName(rhs.GetLastName()),

51:

itsAddress(rhs.GetAddress()),

52:

itsSalary(rhs.GetSalary())

53:

{ }

54:
55:

Employee::Employee() { }

56:
57:Employee & Employee::operator= (const Employee & rhs)
58:

59:

if (this == &rhs)

60:

return *this;

61:
62:

itsFirstName = rhs.GetFirstName();

63:

itsLastName = rhs.GetLastNameO;

64:

itsAddress = rhs.GetAddressO;

65:

itsSalary = rhs.GetSalaryO;

15.

66:
67:

return *this;

68:

69:
70:

void PrintFunc(Employee);

71:

void rPrintFunc(const Employees.);

72:
73:

int main()

74:

75:Employee Edie("Jane","Doe","1461 Shore Parkway", 20000);


76;

Edie.SetSalary(20000);

77:

Edle,Set FirstName(Edythe");

78:

String LastName("Levine");

79:

Edle,SetlastName(LastName);

80:
81:

cout "Constructor count: " ;

82:

oout String;:ConstructorCount << endl;

83:

rPrintFunc(Edie);

84:
85:
86:

cout << "Constructor count: ";


cout << String::ConstructorCount endl;
PrintFunc(Edie);

87:
88:
89:

cout << "Constructor count: ";


cout << String::ConstructorCount endl;
return 0;

90:

91:

void PrintFunc (Employee Edie)

92:

93:
94:
95:

cout << "Name: ";


cout << Edie,GetFirstName().GetString();

96:
97;
98;

cout << " " << Edie.GetLastName().GetString();


cout ",\ nAddress: ";
cout << Edie.GetAddress().GetString();

99:
100:

cout << ",\ nSalary: " ;


cout << Edie.GetSalary();

101:

cout << endl;

102:

103:

104:
105:

void rPrintFunc (const Employee& Edie)

106:

107;

cout << "Name: ";

108:

cout << Edie.GetFirstName().GetString();

109;

cout << " " << Edie.GetLastName().GetString();

110;
111:

cout << "\ nAddress: ";


cout << Edie.GetAddress().GetString();

112:
113:

cout << "\ nSalary: " ;


cout << Edie.GetSalary();

114:

cout << endl;

115:

464

String(char*) constructor
St ring(cha r*) constructor
St ring(cha r*) constructor
String(char*) constructor
String destructor
St ring(char*) constructor
Constructor count: 5
Name: Edythe Levine
Address: 1461 Shore Parkway
Salary: 20000
Constructor count; 5
tring(Strlng&) constructor
String(String&) constructor
String(String&) constructor
Name: Edythe Levine,
Address: 1461 Shore Parkway.
Salary: 20000
String
String

destructor
destructor

String
Constructor

destructor
count; 8

String

destructor

String

destructor

String

destructor

String destructor

Wi'f*1 , , 0 Employee String.


Employee rPrintFuncO ,
Employee .
String. ( , , .)
Employee PrintFuncO ,
Employee String (
-).



. , ,
PartsCatalog. PartsCatalog
, .
PartsCatalog ,
.
, ,
PartsList. ,
PartsCatalog. PartsList
PartsCatalog, PartsCatalog
PartsList.

15,

465

. PartsCatalog
. ,
( public)
.
PartsCatalog PartList?
, .
rtsList,

1. PartsList , PartsCatalog?
, , , .
2.

PartsCatalog
PartsList,
, , .
PartsList?

3.



?
.

, ,
, (.
) . ,
.

, , .

PartsCatalog PartsList? ,
PartsCatalog
PartsList. , PartsList
, ,
. PartsCatalog
.
, PartsList PartsList
public,
InsertO ([]).
.
PartsCatalog, ,
operator+ .
PartsList.

, 15.5.

466

15.5. r t s L i s t ,
r t s C a t a l o g _____________________________
1: #include <iostream.h>
2:

3; II **************** Part ************


4:
5: //
6: class Part
7: {
8: public:
9: Part(): itsPartNumber(1) { }
10: Part(int PartNumber):
11:
itsPartNumber(PartMumber){ }
12: virtual "Part(){ }
13: int GetPartNumber() const
14:

{ return itsPartNumber; }

15: virtual void DisplayQ const =0;


16: private:
17: int itsPartNumber;
18: } ;
19:
20: //
21: //
22: void Part::Display() const
23: {
24: cout << "\ nPart Number: " << itsPartNumber endl;
25: }
26:
27: // ************ **********
28:
29: class CarPart : public Part
30: <
31: public:
32: CarPartO :itsModelYear(94){ >
33: CarPart(int year, int partNumber);
34: virtual void DisplayQ const
35: {
36:

Part::Display();

37:

cout << "Model Year:

38:

cout << itsModelYear << endl;

39: }
40: private:
41: int itsModelYear;
42: } ;
43:
44: CarPart::CarPart(int year, int partNumber):
45: itsModelYear(year),
46: Part(partNumber)
47: { }

15.

467

48:
49:

50:

//

51:
52:

class AlrPlanePart : public Part

53:

54:

public:
AirPlanePart():itsEngineNumbr(1){ } ;
AirPlanePart
(int EnglneNumbsr, int PartNumber);
virtual void DlsplayO const

55:
56:
57:
58:
59:

<

60:

Part::Display ();

61:

cout " Engine No.:


cout itsEngineNumber endl;

62:
63:
64:

65:

private:
int itsEngineNumber;

66:

};

67:
68:
69:
71:

AirPlanePart::AlrPlanePart
(int EngineNumber, int PartNumber):
itsEngineNumber(EngineNumber),
Part(PartNumber)

72:

{)

70:

73:
74:

// ************** **

75:

class PartNode

76:

77:

public:
PartNode (Part*);
PartNode();
void SetNext(PartNode * node)
{ itsNext = node; }
PartNode * GetNextO const;
Part * GetPart() const;
private:
Part *itsPart;
PartNode * itsNext;

78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:

> ;
// PartNode...

89:
90:
91:
92:

PartNode::PartNode(Part pPart):
itsPart(pPart),
itsNext(O)

93:
94:

{>

95:

PartNode::'PartNode()

96:

97:

delete itsPart;

98: itsPart = 0;
99: delete itsNext;
100: itsNext = 0;
101 : }
102 :
103: // NULL, PartNode
104: PartNode * PartNode::GetNext() const
105: <
106:

return itsNext;

107; }
108:
109: Part * PartNode::GetPart() const
110 : {
111: if (itsPart)
112:

return itsPart;

113: else
114:

return NULL; //

115: }
116:
117:
118:
119: // **************** .**.*******
120: class PartsList
121:{

122: public:
123: PartsListO;
124: 'PartsListO;
125: // , -
!
126: void Iterate(void (Part::*f)()const) const;
127: Part* Find(int & position, int PartNumber) const;
128: Part* GetFirstO const;
129: void Insert(Part *);
130: Part* operator[](int) const;
131: int GetCountO const { return itsCount;}
132: static PartsList& GetGlobalPartsListO
133: (
134:

return GlobalPartsList;

135: }
136: private:
137: PartNode * pHead;
138: int itsCount;
139: static PartsList GlobalPartsList;
140: } ;
141:
142: PartsList PartsList::GlobalPartsList;
143:
144:
145: PartsList:: PartsListO :
146: pHead(O),

15.

147:

itsCount(O)

148:

{}

149:
150:

PartsList: : "PartsListO

151:

152:
153:

delete pHead;

154:
155:

Part* PartsList::GetFirst() const

156:

{
if (pHead)

157:

return pHead->GetPart();

158:

else

159:

return NULL; //

160:
161:

162:
163:

Part * PartsList::operator[](int offSet) const

164:

165:

PartNode* pNode = pHead;

166:
167:

if (!pHead)
return NULL; //

168:
169:

if (offSet > itsCount)

170:
171:

return NULL; //

172:
173:

for (int i=0; KoffSet; i++)

174:

pNode = pNode->GetNext();

175:
return pNode->GetPart();

176:
177:

178:

180:

Part* PartsList::Find(
int & position,

181:
182:

179:

int PartNumber) const

183:

PartNode * pNode = 0;

184:

for (pNode = pHead, position = 0;

185:

pNode!=NULL;

186:
187:

pNode = pNode->GetNext(), position++)

{
if

188:

189:

(pNode->GetPart()->GetPartNumber()==

190:

191:

if (pNode == NULL)

192:
193:
194:

PartNumber)

break;

return NULL;
else
return pNode->GetPart();

195:
196:

197: void PartsList::Iterate(void (Part::*func)()const) const


198: {
199: if (!pHead)
200:

return;

201: PartNode* pNode = pHead;


202: do
203:

(pNode->GetPart()->*func)();

204: while (pNode = pNode->GetNext());


205: }
206:
207: void PartsList::Insert(Part* pPart)
208: {
209: PartNode * pNode = new PartNode(pPart);
210: PartNode * pCurrent - pHead;
211: PartNode * pNext = 0;
212 :

213: int New = pPart->GetPartNumber();


214: int Next = 0;
215: itsCount++;
216:
217: if (!pHead)
218: {
219:

pHead = pNode;

220:

return;

221: }
222:

223: // ,
224: //
225: if (pHead->GetPart()->GetPartNumber() > New)
226: {
227:

pNode->SetNext(pHead);

228:
229:

pHead = pNode;
return;

230: }
231:
232: for (;; )
233: {
234:

// ,

235:

if (!pCurrent->GetNext())

236:

237:

pCurrent->SetNext(pNode);

238:
239:

return;
}

240:
241:

// , ,

242:

// . Next

243:

pNext = pCurrent->GetNext();

244:

Next = pNext->GetPart()-> GetPartNumber();

245:

if (Next > New)

246:

15.

247:

pCurrent->SetNext(pNode);

248:

pNode->SetNext(pNext);
return;

249:
250:

}
pCurrent = pNext;

251:
252:

>

253:

254:
255:
256:
257:

class PartsCatalog

258:

<

259:

public:

260:

void Insert(Part *);

261:

int Exists(int PartNumber);

262:

Part * Get(int PartNumber);

263:

operator+(const PartsCatalog &);


void ShowAllO { thePartsList.Iterate(Part:

264:
265:

PartsList thePartsList;

266:
267:

:Display);

private:

};

268:
269:

void PartsCatalog::Insert(Part * newPart)

270:

271:

int partNumber = nawPart->GetPartNumber();

272:

int offset;

273:

if (!thePartsList.Find(offst, partNumber))

274:
275:

thePartsList,Insert(newPart);

276:
277:

else

278:

279:

cout partNumber " ";

280:

switch (offset)

281:

{
case 0: cout << "first "; break;

282:
283:

case 1: cout "second "; break;

284:

case 2: cout "third "; break;


default; cout offset+1 "th ";

285:
286:

}.

287:

cout "entry. Rejected!\ n";

288:
289:

>
}

290:
291:

int PartsCatalog::Exists(int PartNumber)

292:

293:

int offset;

294:

thePartsList.Find(offset,PartNumber);
return offset;

295:
296:

297:

298: Part * PartsCatalog::Get(int PartNumber)


299: {
300: int offset;
301; Part * thePart = thePartsList.Find(offset, PartNumber);
302: return thePart;
303; }
304;
305:
306: int main()
307: {
308: PartsCatalog pc;
309; Part * pPart = 0;
310: int PartNumber;
311: int value;
312: int choice;
313:
314: while (1)
315: {
316: cout "(0)Quit (1)Car (2)Plane: ";
317: cin >> choice;
318;
319: if (Ichoice)
320:
break;
321;
322: cout "New PartNumber?; ";
323: cin PartNumber;
324:
325: if (choice == 1)
326: {
327:

cout "Model Year?; ";

328:

cin value;

329;

pPart = new CarPart(value,PartNumber);

330: }
331: else
332; <
333;

cout "Engine Number?; ";

334:

cin value;

335;

pPart = new AirPlanePart(value,PartNumber);

336: >
337: pc.Insert(pPart);
338: }
339; pc.ShowAllQ;
340: return 0;
341; }

(0)Quit (1)Car (2)Plane: 1


New PartNumber?: 1234
Model Year?: 94

15.

(O)Quit (1)Car (2)Plane: 1


New PartNumber?: 4434
Model Year?: 93
(O)Quit (1)Car (2)Plane: 1
New PartNumber?: 1234
Model Year?: 94
1234 was the first entry. Rejected!
(O)Quit (1)Car (2)Plane: 1
New PartNumber?: 2345
Model Year?: 93
(O)Quit (1)Car (2)Plane: 0
Part Number: 1234
Model Year: 94
Part Number: 2345
Model Year: 93
Part Number: 4434
Model Year: 93

264,
C++.
,
264: void ShowAllO { thePartsList.Iterate(&Part::Display); }

( &)
, ,
, , "".
Part:Display.)

15.5 Part, PartNode PartsList, .


PartsCatalog 257267. PartsList
-, .
, PartsCatalog PartsList.
, PartsCatalog
PartsList. PartsList PartsCatalog,
. , PartsCatalog: :Insert()
, PartsList.
PartsCatalog: :Insert() 269.
Part, , itsPartNumber.
Find() PartsList,
, .
.
, InsertO PartCatolog
- thePartList, PartList.
,
PartsList,
- PartsCatalog.
PartsCatalog,
PartsList.

474

C++.
, PartsLists,
, PartsCatalog.
PartsCatalog PartsList.
PartsList ( )
, PartsCatalog.

PartsCatalog

( ) PartsCatalog

PartsList

PartsList, PartsList.

, PartsCatalog PartsList

PartsList

PartsCatalof, .
, :
- ,
, . ,
, - PartsCatalog, ,
PartsList. :
.
PartsList PartsCatalog.
PartsList .
PartsCatalog,
PartsList, PartsCatalog
PartList. , PartsCatalog PartsList,
. PartsCatalog
PartsList, .
.

15.6.

PartsCatalog private PartsList.

15.. ______________________________________________
1:

// 15.6.

2:

include <iostream.h>

3:
4:

// **************** Part ************

5:

6:

//

7:

class Part

8:

<

9:

public:

10: Part():itsPartNumber(1) { }
11: Part(int PartNumber):
12:

itsPartNumber(PartNumber){ }

13: virtual 'Part(){ }


14: int GetPartNumber() const

15.

475

15:

{ return itsPartNumber; }

16:

virtual void DisplayO const =0;

17:

private:
int itsPartNumber;

18:
19:

};

20:
21:
22:

//

23:

void Part::Display() const

24:

//

25:
26:

cout << "\ nPart Number: " << itsPartNumber << endl;

27:
28:

II

**************** Qa Pa rt ************

29:
30:

class CarPart : public Part

31:

32:

public:

33:
34:

CarPart():itsModelYear(94){ }
CarPart(int year, int partNumber);

35:

virtual void DisplayO const

36:

37:

Part::Display();

38:

cout << "Model Year: ";


cout << itsModelYear endl;

39:
40:
41:

>
private:
int itsModelYear;

42:
43:

};

44:
45:

CarPart::CarPart(int year, int partNumber):


itsModelYear(year),

46:
47:
48:

Part(partNumber)

{}

49:
50:
51:

// *********** AirPlane Part *****

52:
53:

class AirPlanePart : public Part

54:

<

55:

public:

56:

AirPlanePartO :itsEnginsNumber(1)< } ;

57:

AirPlanePart
(Int EngineNumber, int PartNumber);

58:
59:

virtual void DisplayO const

60:

<

61:

Part::DisplayO;

62:

cout << "Engine No.: ";


cout << itsEngineNumber endl;

63:
64:

>

65: private:
66: int itsEngineNumber;
67: } ;

68:
69: AirPlanePart::AirPlanePart
70: (Int EngineNumber, int PartNumber):
71: itsEngineNumber(EngineNumber),
72: Part(PartNumber)
73: { }
74:
75: // ************ Part Node ************
76: class PartNode
77: {
78: public:
79: PartNode (Part*);
80: -PartNodeO;
81: void SetNext(PartNode * node)
82: { itsNext = node; }
83: PartNode * GetNextO const;
84: Part * GetPartO const;
85: private:
86: Part *itsPart;
87: PartNode * itsNext;

88: } ;
89: // PartNode...
90:
91: PartNode::PartNode(Part* pPart):
92: itsPart(pPart),
93: itsNext(O)
94: { >
95:
96: PartNode::'PartNode()
97: {
98: delete itsPart;
99: itsPart = 0;
100: delete itsNext;
101: itsNext = 0;
102: }
103:
104: // NULL NULL, PartNode
105: PartNode * PartNode: :GetNextO const
106: {
107:

return itsNext;

108: }
109:
110: Part * PartNode::GetPart() const

111: {
112: if (itsPart)
113:

return itsPart;

114: else

15.

115:
116:

return NULL; //

117:
118:
119:

120 :
121 :

// ************ Part List ************


class PartsList

122:

<

123:

public:

124:

PartsList();

125:
126:

~PartsList();
// , -

127:

void Iterate(void (Part::*f)()const) const;

128:

Part* Find(int & position, int PartNumber) const;

129:

Part* GetFirst() const;

130:

void Insert(Part *);

131:

Part* operator[ ](int) const;

132:

int GetCount() const { return itsCount; }


static PartsList& GetGlobalPartsList()

133:
134:

135:

return GlobalPartsList;

136:
137:

>
private:

138:

PartNode * pHead;

139:

int itsCount;

140:

static PartsList GlobalPartsList;

141:

};

142:
143:

PartsList PartsList::GlobalPartsList;

144:
145:
146:

PartsList::PartsList():

147:

pHead(O),
itsCount(O)

148:
149:

{>

150:
151:

PartsList::"PartsList()

152:

153:
154:

delete pHead;

155:
156:

Part* PartsList::GetFirst() const

157:

{
if (pHead)

158:
159:

return pHead->GetPart();

160:

else
return NULL; //

161:
162:

163:

164: Part * PartsList::operator[](int offSet) const


165: {
166: PartNode* pNode = pHead;
167:
168: if (!pHead)
169:
return NULL; //
170:
171: if (offSet > itsCount)
172:
return NULL; //
173:
174: for (int i=0;i<offSet; i++)
175:
pNode = pNode->GetHext();
176:
177: return pNode->GetPart();
178: }
179:
180: Part* PartsList::Find(
181:

int & position,

182:

int PartNumber) const

183: {
184: PartNode * pNode = 0;
185: for (pNode = pHead, position = 0;
186:
187:
188: {
189:
190:

pNode!=NULL;
pNode = pNode->GetNext(), position++)
if (pNode->GetPart()~>GetPartNumber() == PartNumber)
break;

191: }
192: if (pNode == NULL)
193:

return NULL;

194: else
195:

return pNode->GetPart();

196: }
197:
198: void PartsList::Iterate(void (Part::*func)()const) const
199: {
200: if (!pHead)
201:

return;

202: PartNode* pNode = pHead;


203: do
204:

(pNode~>GetPart( )->*func) ();

205: while (pNode = pNode->GetNext());


206: }
207:
208: void PartsList::Insert(Part* pPart)
209: {
210: PartNode * pNode = new PartNode(pPart);
211: PartNode * pCurrent = pHead;
212: PartNode * pNext = 0;
213:

15.

214:

int New = pPart->GetPartNumber();

215:

int Next = 0;

216:

itsCount++;

217:
if (!pHead)

218:
219:

220:

pHsad = pNode;

221 :

return;

222:

223:
224:

// ,

225:

//

226:
227:

if (pHead->GetPart()->GetPartNumber() > New)

228:

pNode->SetNext(pHead);

229:

pHead = pNode;
return;

230:
231:

>

232:
233:
234:

for (;;)

<

236:

// ,
if (!pCurrent->GetNext())

237:

235:

pCurrent->SetNext(pNode);

238:

return;

239:
240:

241:
242:

// , ,

243:

// , Next

244:

pNext = pCurrent->GetNext();
Next = pNext->GetPart()->GetPartNumber();

245:

if (Next > New)

246:
247:

{
pCurrent->SetNext(pNode);
pNode->SetNext(pNext);

248:
249:

return;

250:
251:

}
pCurrent = pNext;

252:
253:

254:
255:
256:
257:
258:

class PartsCatalog : private PartsList

259:

260:

public:

261:

void Insert(Part *);

262:

int Exists(int PartNumber);

263:

Part * Get(int PartNumber);

264: operator+(const PartsCatalog &);


265: void ShowAll() { Iterate(Part::Display); >
266: private:
267: } ;
268:
269: void PartsCatalog::Insert(Part * newPart)
270: {
271: int partNumber = newPart->GetPartNumber();
272: int offset;
273:
274: if (!Find(offset, partNumber))
275: PartsList::Insert(newPart);
276: else
277: {
278: cout << partNumber << " was the
279: switch (offset)
280: {
281:

case 0: cout << "first break:

282:
283:

case 1: cout << "second break;


case 2: cout << "third break;

284:

default: cout << offset+1 << "th ";

285: }
286: cout << "entry. Rejected!\ n";
287: }
288: }
289:
290: int PartsCatalog::Exists(int PartNumber)
291: {
292: int offset;
293: Find(offset,PartNumber);
294: return offset;
295: }
296:
297: Part * PartsCatalog::Get(int PartNumber)
298: {
299: int offset;
300: return (Find(offset, PartNumber));
301:
302: }
303:
304: int main()
305: {
306: PartsCatalog pc;
307: Part * pPart = 0;
308: int PartNumber;
309: int value;
310: int choice;
311:
312: while (1)
313: {

15.

314: cout << "(O)Quit (1)Car (2)Plane:


315: cin >> choice;
316:
317: if ('choice)
318:
break;
319:
320: cout << "New PartNumber?: ";
321: cin >> PartNumber;
322:
323: if (choice == 1)
324: {
325:

cout << "Model Year?: ";

326:

cin >> value;

327:

pPart = new CarPart(value,PartNumber);

328: }
329: else
330: {
331:
332:

cout << "Engine Number?:


cin >> value;

333:

pPart = new AirPlanePart(value,PartNumber);

334: }
335: pc.Insert(pPart);
336: }
337: pc.ShowAll();
338: return 0;
.339; }

(O)Quit (1)Car (2)Plane: 1


New PartNumber?: 1234
Model Year?: 94
(O)Quit (1)Car (2)Plane: 1
New PartNumber?: 4434
Model Year?: 93
(O)Quit (1)Car (2)Plane: 1
New PartNumber?: 1234
Model Year?: 94
1234 was the first entry. Rejected!
(O)Quit (1)Car (2)Plane: 1
New PartNumber?: 2345
Model Year?: 93
(O)Quit (1)Car (2)Plane: 0
Part Number: 1234
Model Year: 94
Part Number: 2345
Model Year: 93
Part Number: 4434
Model Year: 93

482

15.6 PartsCatalog
main(). ,
15.5.
258 15.6 PartsCatalog private
Partslist. PartsCatalog , 15.5, ,
, PartsList - .
- ShowAll()
PartsCatalog
Iterate()

Partslist, - Part.
, ShowAllO ,
,
IterateO, PartsCatalog.
Insert() . , 274
Find() ,
. InsertO
, 275 .
, PartsCatalog
PartsList, . ,
PartsList
.
PartsCatalog
, ,
.

,

.
,

,
.

,



.


,

.

. ,
1
^^
.

,

.

-
, ,
. , ;1
^ , , PartsList
1 11^.
, ^
-, ,
.
^^, .

15.

483

, -
, .
-.
PartsNode PartsList , PartsNode PartsList.
, .
, , , ,
. , . ,
, , .
, .
- .
, ,
.
15.7 15.6,
. , PartsList PartNode.
, PartNode PartsList.

15.7. -_____________________________________________
1: include <iostream.h>
2:
3:
4:
5:
6: // **************** Part ************
7:
8: //
9: class Part

10: {
11: public:
12: Part():itsPartNumber(1) { }
13: Part(int PartNumber):
14:
itsPartNumber(PartNumber){ }
15: virtual "Part(){ }
16: int GetPartNumberO const
17:
{ return itsPartNumber; }
18: virtual void DisplayO const =0;
19: private:
20: int itsPartNumber;

21: } ;
22:

23: //
24: //
25: void Part:: DisplayO const
26: {
27:

cout "\ nPart Number: ";

28:

cout << itsPartNumber << endl;

29: >
30:
31: // ************** Car Part ************
32:

484

33: class CarPart : public Part


34: {
35: public:
36: CarPart():itsModelYear(94){ }
37: CarPart(int year, int partNumber);
38: virtual void DisplayO const
39: {
40:

Part::Display();

41:

cout << "Model Year:

42:

cout itsModelYear << endl;

43: }
44: private:
45: int itsModelYear;
46: } ;
47:
48: CarPart::CarPart(int year, int partNumber):
49: itsModelYear(year),
50: Part(partNumber)
51: { >
52:
53:
54: // *********** AirPlane Part ***********
55:
56: class AirPlanePart : public Part .
57: {
58: public:
59: AirPlanePart():itsEngineNumber(1){ > ;
60: AirPlanePart
61:

(int EngineNumber, int PartNumber);

62: virtual void DisplayO const


63: {
64:

Part::Display();

65:
66:

cout << "Engine No.: ";


cout << itsEngineNumber endl;

67: }
68: private:
69: int itsEngineNumber;
70: } ;
71:
72: AirPlanePart::AirPlanePart
73: (int EngineNumber, int PartNumber):
74: itsEngineNumber(EngineNumber),
75: Part(PartNumber)
76: { }
77:
78: // **************** Part Node ************
79: class PartNode
80: {
81: public:
82: friend class PartsList;

15.

485

83: PartNode (Part*);


84: "PartNodeO;
85: void SetNext(PartNode * node)
86:

{ itsNext = node; }

87: PartNode * GetNextO const;


88: Part * GetPartO const;
89: private:
90: Part *itsPart;
91: PartNode * itsNext;
92: } ;
93:
94:
95: PartNode::PartNode(Part* pPart):
96: itsPart(pPart),
97: itsNext(O)
98: { }
99:
100: PartNode::"PartNode()
101: {
102:

delete itsPart;

103:
itsPart = 0;
104: ' delete itsNext;
105:

itsNext = 0;

106: }
107:
108:

// NULL, PartNode

109:

PartNode * PartNode::GetNext() const

110 : {
111:

return itsNext;

112: }
113:
114:

Part * PartNode::GetPart() const

115:

116:
117:

if (itsPart)
return itsPart;

118:

else

119:

return NULL; //

120: }
121:
122:
123: // ************** Part List ************
124: class PartsList
125: {
126: public:
127: PartsListQ;
128: "PartsListO;
129: // ,

!
130: void Iterate(void (Part::*f)()const) const;
131: Part* Find(int & position, int PartNumber) const;

486

132: Part* GetFirstO const;


133: void Insert(Part *);
134: Part* operator[](int) const;
135: int GetCountO const { return itsCount; }
136: static PartsList& GetGlobalPartsListO
137:
138:

139:

return GlobalPartsList;

140: private:
141: PartNode * pHead;
142: int itsCount;
143: static PartsList GlobalPartsList;
144: } ;
145:
146: PartsList PartsList::GlobalPartsList;
147:
148: // Implementations for Lists...
149:
150: PartsList::PartsList():
151: pHead(O),
152: itsCount(O)
153: { }
154:
155: PartsList::'PartsList()
156: {
157: delete pHead;
158: }
159:
160: Part* PartsList::GetFirst() const
161: {
162: if (pHead)
163:

return pHead->itsPart;

164: else
165:

return NULL; //

166: }
167:
168: Part * PartsList::operator[](int offSet) const
169: {
170: PartNode* pNode = pHead;
171:
172: if (!pHead)
173: return NULL; //
174:
175: if (offSet > itsCount)
176: return NULL; //
177:
178: for (int i=0;icoffSet; i++)
179:
pNode = pNode->itsNext;
180:
181: return pNode->itsPart;

15.

182:

>

183:
184:
185:

Part* PartsList::Find(int & position, int PartNumber) const

<
PartNode * pNode = 0;
for (pNode = pHead, position = 0;

186:
187:
188:
189:

pNode!=NULL;
pNode = pNode->itsNext, position++)

190:

{
if (pNode->itsPart->GetPartNumber() == PartNumber)

191:

break;

192:
193:

194:

if (pNode == NULL)

195:

return NULL;

196:

else
return pNode->itsPart;

197:
198:
199:

200:

201:
202 :

void PartsList::Iterate(void (Part::*func)()const) const

{
if (!pHead)
return;

203:
204:

PartNode* pNode = pHead;

205:

do

206:

(pNode->itsPart->*func)();

207:

while (pNode = pNode->itsNext);

208:

209:

210:

void PartsList::Insert(Part* pPart)

211:

{
PartNode * pNode = new PartNode(pPart);

212:
213:

PartNode * pCurrent = pHead;

214:

PartNode * pNext = 0;

215:
216:
217:

int New = pPart->GetPartNumber();

218:
219:

itsCount++;

220 :

if (!pHead)

221:

int Next = 0;

222:

pHead = pNode;

223:
224:

return;

225:
226:
227:

// ,

228:

if (pHead->itsPart->GetPartNumber() > New)

229:

230:
231:

//

pNode->itsNext = pHead;
'pHead = pNode;

232: return;
233: >
234:
235: for (:;)
236: <
237:

// ,

238: if (!pCurrent->itsNext)
239: {
240:

pCurrent->itsNext = pNode;

241:

return;

242:

243:
244:

// , ,

245:

// . Next

246: pNext = pCurrent->itsNext;


247:
Next = pNext->itsPart->GetPartNumber();
248:

if (Next > New)

249:
250:
251:

{
pCurrent->itsNext = pNode;
pNode->itsNext = pNext;

252:
253: >
254:

return;
pCurrent = pNext;

255: >
256: }
257:
258: class PartsCatalog : private PartsList
259: {
260: public:
261: void Insert(Part *);
262: int Exists(int PartNumber);
263: Part * Get(int PartNumber);
264: operator+(const PartsCatalog &);
265: void ShowAll() { Iterate(Part::Display); }
266: private:
267: > ;
268:
269: void PartsCatalog::Insert(Part * newPart)
270: {
271: int partNumber = newPart->GetPartNumber();
272: int offset;
273:
274: if (!Find(offset, partNumber))
275: PartsList::Insert(newPart);
276: else
277: {
278:

cout << partNumber << " was the ";

279: switch (offset)


280: {
281:

case 0: cout << "first "; break;

15.

282:

case 1: cout << "second "; break;

283:

case

284:

default: cout offset+1 << "th ";

2:

cout

<<

"third

285:

286:

cout << "entry. Rejected!\ n";

287:
288:

break;

}
}

289:
290:
291:

int PartsCatalog::Exists(int PartNumber)

292:

int offset;

293:

Find(offset,PartNumber);

294:
295:

return offset;

296:
297:

Part * PartsCatalog::Get(int PartNumber)

298:

299:
300:
301:

int offset;
return (Find(offset, PartNumber));

302:
303:
304:

int main()

305:

<

306:

PartsCatalog pc;

307:

Part * pPart = 0;

308:

int PartNumber;

309:

int value;

310:

int choice;

311:
312:

while (1)

313:

<

314:

cout << "(0)Quit (1)Car (2)Plane:

315:

cin >> choice;

316:
317:

if (!choice)
break;

318:
319:
320:

cout << "New PartNumber?: ";

321:

cin >> PartNumber;

322:
323:

if (choice == 1)

324:

325:

cout << "Model Year?:

326:

cin >> value;

327:

pPart = new CarPart(value,PartNumber);

328:

329:

else

330:

331:

cout << "Engine Number?: ";

332:

>> value;

333:

pPart = new AirPlanePart(value,PartNumber);

334: >
335: pc.Insert(pPart);
336: }
337: pc.ShowAllO;
338: return 0;
339: }

......

(O)Quit (1)Car (2)Plane: 1


New PartNumber?: 1234
Model Year?: 94
(O)Quit (1)Car (2)Plane: 1
New PartNumber?: 4434
Model Year?: 93
(O)Quit (1)Car (2)Plane: 1
New PartNumber?: 1234
Model Year?: 94
1234 was the first entry. Rejected!
(O)Quit (1)Car (2)Plane: 1
New PartNumber?: 2345
Model Year?: 93
(O)Quit (1)Car (2)Plane: 0
Part Number: 1234
Model Year: 94
Part Number: 2345
Model Year: 93
Part Number: 4434
Model Year: 93

82 PartsList PartNode.
public
PartNode, .
, .
-
PartNode - PartsList.
160 - GetFirstO
. pHead->GetPart
- pHead->itsPart.
InsertO pNode->itsNext = pHead
- pHead->SetNext(pHead).
,
PartsList PartNode.
, friend.
- .
- ,

15.

491


.
.

++
, -
, -
. , ,
. -
, ,
.


-
friend
. , ,
.
:

"

friend class PartsList: // Partslist PartNode

-
,
-.
- .
. ,
, - .

-
15.1 String, operator+.
,
, String
.

492

C++ ,
. ,
, : myString[] = "Hello World".

:'

String,
:
char cSt ring[] = { "Hello"} ;
String sString(" World");
String sStringTwo = cString + sString; //!

operator+.
10, cSt ring + sString
cString.operator+(sString). operator+()
, .
, - String,
operator+ , String.
String String,
- operator+, .

15.8. - o p e r a t o r ______________________________________________ _
1:

// 15.8.

2:

3:

include <iostream.h>

4:

include <string.h>

5:
6:

// string

7:

class String

8:

9:

public:

10:

// constructors

11:
12:

StringO;
String(const char *const);

13:
14:.

String(const String &);


'StringO;

15:
16:

//

17:

char & operator[](int offset);

18:
19:

char operator[](int offset) const;


String operator+(const String&);

20:friend String operator+(const String&, const String&);


21:

void operator+=(const String&);

22:

String & operator= (const String &);

23:
24:

//

25:

int GetLen()const { return itsLen; }

26:const char * GetStringO const { return itsString; }


27:
28:

private:

29:

String (int); //

30:

char * itsString;

31:

unsigned short itsLen;

32:

> ;

33:

15.

493

34:// , , 0
35:

String::String()

36:
37:
38:

{
itsString = new char[1];
itsString[0] = \ O';

39:

itsLen=0;

40:

// cout << "\ tDefault string constructor\ n";

41:

// ConstructorCount++;

42:

43:
44:

// ,

45:

//

46:

// , .

47:

String::St ring(int len)

48:

49:

itsString = new char[len+1];

50:

for (int i = 0; i<=len; i++)

51:
52:
53:

itsString[i] = '\ 0;
itsLen=len;
// cout << "\ tString(int) constructor\ n";

54:

// ConstructorCount++;

55:

56:
57:

//

58:

String::St ring(const char * const cString)

59:
60:

{
itsLen = strlen(cString);

61:

itsString = new char[itsLen+1];

62:

for (int i = 0; KitsLen; i++)

63:

itsSt ring[i] = cSt ring[i];

64:

itsString[itsLen]='\ 0;

65:
66:
67:

// cout << "\ tString(char*) constructor\ n";


// ConstructorCount++;
>

68:
69:

// -

70:

String::String (const String & rhs)

71:
72:

{
itsLen=rhs.GetLen();

73:

itsString = new char[itsLen+1];

74:

for (int i = 0; KitsLen; i++)

75:

itsString[i] = rhs[i];

76:

itsString[itsLen] = \ O;

77:

// cout "\ tString(String&) constructor\ n";

78:

// ConstructorCount++;

79:
80:

81:

// ,

82:

String::"String ()

83:

494

84:

delete [] itsString;

85:

itsLen = 0;

86:

// cout << "\ tString destructor\ n";

87:

88:
89:
90:

// ,
//

91:

String& String::operator=(const String & rhs)

92:
93:

{
if (this == &rhs)

94:

return *this;

95:

delete [] itsString;

96:

itsLen=rhs.GetLen();

97:

itsString = new char[itsLen+1];

98:

for (int i = 0; i<itsLen;i++)

99:
100:

itsString[i] = rhs[i];
itsString[itsLen] = 1\ O;

101:

return *this;

102:

// cout << "\ tString operator=\ n";

103:
104:
105:

}
// ,

106:

// ,

107:

// !

108:

char & String::operator[](int offset)

109:

110:

if (offset > itsLen)

111:

return itsString[itsLen-1 ];

112:

else

113:
114:

return itsString[offset];
}

115:
116:

// ,

117:// (. -
118:

char String::operator[](int offset) const

119:

120:

if (offset > itsLen)

121:

return itsString[itsLen-1];

122:

else

123:

return itsString[offset];

124:

125:

// String,

126:

// rhs

127:

String String::operator+(const String& rhs)

128:

129:
130:

int totalLen = itsLen + rhs.GetLen();


String temp(totalLen);

131:
132:

int i, j;
for (i = 0; i<itsLen; i++)

133:

temp[i] = itsString[i ];

15.

134:

for (j = 0, i = itsLen; j<rhs.GetLen(); j++, i++)


temp[i] = rhs[j];

135:

temp[totalLen]=\ 0;

136:

return temp;

137:
138:

139:
140:
141:

// String

142:

String operator+(const String& lhs, const String& rhs)

143:

// String

144:

int totalLen = lhs.GetLen() + rhs.GetLen();

145:

String temp(totalLen);

146:
147:

int i, j;
for (i = 0; i<lhs.GetLen(); i++)

148:
149:

for (j = 0, i = lhs.Getlen();; j<rhs.GetLen(); j++, i++)

temp[i] = lhs[i ];
temp[i] = rhs[j];

150:

temp[totalLen]='\ O';

151:
152:
153:

return temp;

>

154:
155:

int main()

156:

<

157:

String s1("String One );

158:

String s2("String Two ");

159:

char *c1 = { "-String One " } ;

160:

String s3;

161:

String s4;

162:

String s5;

163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:

s1.GetString()
cout << "s1:
cout << s2: ' s2.GetString()
cout << "c1: ' << c1 << endl;
s3 = s1 + s2;
cout "S3: ' << s3.GetString()
s4 = s1 + cl;
cout "s4: ' s4.GetString()
s5 = C1 + s2;
cout "s5:

<< s5.GetString()

endl;

endl;

<< endl;
<< endl;

endl;

return 0;

174:

s1: String One


s2: String Two
c1: -String One
s3: String One String Two
s4: String One -String One
s5: -String One String Two

String, operator+,
, 15.1. 20 15.8
operator+,
, .
String.
, operator+ -
. - string
, .
, .
operator+ 142153.
,
15.1,
, .
171,
.

-
friend,
.
this,
-.
:
Class PartNode
.|:^r i ,.

riieod .vioidcrtsl.ist,;-::Inse

-,

://: :01' :::,

friend int SomeFunctionO;


String cout
, .
-
:
cout theString.GetStringO;


cout << theString;

operator<<().
iost reams 16.
15.9 operator .

15.

497

15.8. o p e r a t o r < < ( )


1:

include <iostream.h>

2:

include <string.h>

3:
4:

class String

5:
6:
7:

{
public:
//

8:

StringO;

9:

String(const char const);

10:

String(const String &);

11:

'StringO;

12:
13:

//

14:

char & operator[](int offset);

15:

char operator[](int offset) const;

16:

String operator+(const String&);

17:

void operator+=(const String&);

18:
19:

String & operator= (const String &);


friend ostream& operator

20:

( ostream& theStream,String& theString);

21:

//

22:
int GetLen()const { return itsLen; }
23: const char * GetStringO const { return itsString; }
24:
25:

private:

26:

String (int); //

27:

char * itsString;

28:

unsigned short itsLen;

29:
30:

} ;

31:
32:// , , 0
33:

String::St ring()

34:

<

35:

itsString = new char[1];

36:

itsString[0] = \ O;

37:

itsLen=0;

38:

// cout "\ tDefault string constructor\ n";

39:

// ConstructorCount++;

40:

41:
42:

// ,

43:

//

44: // , NULL,
45:
String::String(int len)
46:

<

47:

itsString = new char[k:.t1];

48:

for (int i = 0; i<=len, i++)

498

49:
50:

itsString[i] = ' \ O' ;


itsLen=len;

51:

11 cout "\ tString(int) constructor\ n";

52:

// ConstructorCount++;

53:

54:
55:

//

56:

String::St ring(const char * const cString)

57:
58:

{
itsLen = strlen(cString);

59:

itsString = new char[itsLen+1];

60:

for (int i = 0; icitsLen; i++)

61:

itsString[i] = cSt ring[i ];

62:

itsString[itsLen]=\ 0;

63: // cout << "\ tString(char*) constructor\ n";


64:

// ConstructorCount++;

65:

66:
67:

// -

68:

String::String (const String & rhs)

69:
70:

{
itsLen=rhs.GetLen();

71:

itsString = new char[itsLen+1];

72:

for (int i = 0; i<itsLen;i++)

73:
74:

itsString[i] = rhs[i];
itsString[itsLen] = '\ O;

75: // cout "\ tString(String&) constructor\ n";


76:

// ConstructorCount++;

77:

78:
79:

//

80:

String::_String ()

81:
82:

{
delete [] itsString;

83:
84:

itsLen = 0;
// cout "\ tString destructor\ n";

85:

86:
87:// ,
88:

//

89: String& String::operator=(const String & rhs)


90:

<

91:

if (this == &rhs)

92:

return *this;

93:
94:

delete [] itsString;
itsLen=rhs.GetLen();

95:

itsString = new char[itsLen+1];

96:

for (int i = 0; icitsLen;i++)

97:

itsString[i] = rhs[i ];

98;

itsString[itsLen] = \ O';

15.

99:

return *this;

100:
101:

// cout "\ tString operator=\ n";

102 :
103:
104:

// ,
// ,

105: // !
106:

char & String::operator[](int offset)

107:

108:

if (offset > itsLen)


return itsString[itsLen-1];

109:

110:

else

111 :
112:

return itsString[offset];

>

113:
114:

// ,

115:

// (. -!)

116:
117:

char String::operato[](int offset) const

118:
119:

if (offset > itsLen)


return itsString[itsLen-1];

120 :

else
return itsString[offset];

121:
122:

123:
124:

// ,

125:

// rhs

126:

String String::operator+(const String& rhs)

127:

128:
129:

int totallen = itsLen + rhs.GetLen();


String temp(totalLen);

130:
131:

int i, j;
for (i = 0; icitsLen; i++)
temp[i] = itsSt ring[i];

132:
133:

for (j = 0; j<rhs.GetLen(); j++, i++)

134:

temp[i ] = rhs[j ];

135:

temp[totalLen]='\ 0';
return temp;

136:
137:

>

138:
139:

// ,

140:

void String::operator+=(const String& rhs)

141:

142:

unsigned short rhsLen = rhs.GetLen();

143:
144:

String temp(totalLen);

145:

int i, j;

146:

for (i = 0; KitsLen; i++)

147:
148:

unsigned short totalLen = itsLen + rhsLen;

temp[i]

itsString[i];

for (j = 0, i = 0; j<rhs.GetLen(); j++, i++)

149: temp[i] = rhs[i-itsLen];


150: temp[totalLen]='\ O';
151: *this = temp;
152: }
153:
154: // int String::ConstructorCount =
155: ostream& operator ( ostream& theStream,String& theString)
156: {
157: theStream << theString.itsString;
158: return theStream;
159: }

160:
161: int main()
162: {
163: String theString("Hello world.");
164: cout << theString;
165: return 0;
166: }

Hello world.

19 operator -,
ostream String ostream.
, - String.
ostream, operator :
cout << "myAge: " << itsAge << " years. ";

- 155159.
,
iostream. .
operator .

,
,
.

- . ,
, .
, - .
,
cout
, .
,
;
,
. ,
, .

15.

501



?
C++ . -

,
,
.

?


.
,
.
, .

, ,
?
-
, .
.

,
?
.
,
friend.


,
.
, .
,
, .


1. , ?
2. ,
- ?
3. ?

4.
?

502

5. -?
6. -?
7. Dog , , Dog?
8. Dog Boy, a Terrier Dog,
Terrier ?
9. Dog , House, Dog
House?
10. -?

1. Animal, -,
String.
2. BoundedArray, .
3. Set, BoundedArray.
4. 15.1 , String
(>>).
5. : :
1

include <iostream.h>

2
3

class Animal;

4
5

void setValue(Animal& , int);

6
7

class

10

public:
int GetWeight()const { return itsWeight;

11
12
13
14
15

Animal

int GetAgeO const { return itsAge; }


private:
int itsWeight;
int itsAge;

16
17
18

void setValue(Animal& theAnimal, int theWeight)

19

20
21

friend class Animal;


theAnimal.itsWeight = theWeight;

22
23
24

int main()

25
26

Animal peppy;

27

setValue(peppy,5);

28

15.

503

6. , 5, .
7. : :
1: include <iostream.h>

2:
3: class Animal;
4:
5: void setValue(Animal& , int);
6: void setValue(Animal& ,int,int);
7:
8: class Animal
9: {
10: friend void setValue(Animal& ,int);
11: private:
12: int itsWeight;
13: int itsAge;
14: > ;
15:
16: void setValue(Animal& theAnimal, int theWeight)
17: {
18: theAnimal.itsWeight = theWeight;
19: }
20:

21:
22: void setValue(Animal& theAnimal, int theWeight, int theAge)
23: {
24: theAnimal.itsWeight = theWeight;
25: theAnimal.itsAge = theAge;
26: }
27:
28: int main()
29: {
30: Animal peppy;
31: setValue(peppy,5);
32: setValue(peppy, 7, 9);
33: }

8. , 7, .

504



, . :


C++ ,
.
,
C++ iostream, - (I/O).
-
.
C++ PC,
Sun.
. , , .

,

.
, , ,

.

, ,
. ,
, , .

16.

505

, .
.

.
, .
. 16.1.

^3 ^30^3^3 (XXX] 9 V

. 16.1.

( ) .
,
.
.
, .

. (. 16.2). , ,
.
() ,
(. 16.3).
, ,
, (. 16.4).
, ,
.
(. 16.5).

506

. 16.3. , ()

16.

508


C++ -
.

streambuf ,
, , .

ios -. - ios streambuf.

ist ream ostream ios


.

iosteam istream ostream


- .

fst ream - .

-
, iost reams,
.

iost ream .
,
#include<iostream>.

cin ( - see-in)
.

cout ( - see-out)
.

( - see-err)

, .. . , ,
, .

clog ( - see-log)
,
(). . .

,
, .
, .
,
.

16.

509

,
, .
11
(<) (>).

.

(>) (<). 11 ,
: ,
.
.
,
1!. ++
-.

ein
ein
iostream.
()
. :
int someVariable',
cout << "Enter a number:
ein >> someVariable:

, cout,
. : ein someVariable;.
ein?
,
. ein (),
, ein, someVariable.
,
, int&, short&, long&, doubles., floats., char&, char* ..
ein someVariable, ,
someVariable. someVariable
int, :
istream 8< operator (int&)

, ,
. ein 16.1.

16.1. ein _________________________


1: // 16.1. ein

2
3

(/include <iostream.h>

4
5

int main()

6
7

510

int mylnt;

8:

long myLong;

9:

double myDouble;

10:

float myFloat;

11:

unsigned int myUnsigned;

12:

13:
14:

cout "int:
cin >> mylnt:

15:
16:

cout << "Long:


cin >> myLong;

17:
18:

cout "Double:
cin >> myDouble;

19:

cout << "Float: ";

20:

cin myFloat;

21:
22:

cout << "Unsigned: ";


cin >> myUnsigned;

23:
24:
25:

cout "\ n\ nlnt:\ t" mylnt endl;


cout << "Long:\ t" << myLong << endl;

26:
cout << "Double:\ t" << myDouble << endl;
27:
cout << "Float:\ t" << myFloat << endl;
28:
cout "Unsigned:\ t" << myUnsigned endl;
29: return 0;
30: }

int: 2
Long: 70000
Double: 987654321
Float: 3.33
Unsigned: 25
Int: 2
Long: 70000
Double: 9.87654e+08
Float: 3.33
Unsigned:

25

711 . 1322
,
2428 ( ein).
,
.

ein
(char*), ein.
, :
char YourName[50]
cout << "Enter your name: ";
cin >> YourName;

16.

511

Jesse, YourName J, , s, s, \0.


, .
,
,
.
21.

,
,
, . ,
.
,
. 16.2.

1.2.
1:

// 16.2. cin

2:
3:
4:

Sinclude <iostream.h>

5:

int main()

6:

7:

char YourNaine[50];

8:

cout << "Your first name:

9:

cin >> YourName;

10:

cout << "Here it is: " << YourName << endl;

11:

cout "Your entire name: ";

12:

cin >> YourName;

13:

cout << "Here it is: " << YourName << endl;

14:

return 0;

15:

Your first name: Jesse


Here it is: Jesse
Your entire name: Jesse Liberty
Here it is: Jesse

7
. 8 , ,
, .
11 , .
, cin
. .
, .
, cin , 16.3,
.

512

16.3.
1: // 16.3. cin

2:
3: include <iostream.h>
4:
5: int main()

6: {
7:
8:

int mylnt;
long myLong;

9:

double myDouble;

10:

float myFloat;

11:

unsigned int myUnsigned;

12:

char myWord[50];

13:
14:

cout "int:

15:

cin >> mylnt;

16:

cout << "Long: ";

17:

cin myLong;

18:
19:

cout << "Double: ";


cin >> myDouble;

20:

cout << "Float: ";

21:

cin >> myFloat;

22:
23:

cout "Word: ";


cin >> myWord;

24:

cout << "Unsigned: ";

25:

cin >> myUnsigned;

26:
27:

cout << "\ n\ nlnt:\ t" << mylnt << endl;

28:

cout << "Long:\ t" << myLong << endl;

29:

cout << "Double:\ t" << myDouble endl;

30:

cout << "Float:\ t << myFloat << endl;

31:
32:

cout "Word: \ t" << myWord << endl;


cout << "Unsigned:\ t" << myUnsigned << endl;

33:
34:cout << "\ n\ nlnt, Long, Double, Float, Word, Unsigned: ";
35:

cin >> mylnt myLong >> myDouble;

36:

cin >> myFloat >> myWord >> myUnsigned;

37:

cout << "\ n\ nlnt:\ t" << mylnt << endl;

38:

cout << "Long:\ t" << myLong << endl;

39:

cout << "Double:\ t" << myDouble << endl;

40:

cout << "Float:\ t" << myFloat << endl;

41:

cout "Word: \ t" << myWord << endl;

42:

cout << "Unsigned:\ t" << myUnsigned << endl;

43:
44:
45:

return 0;

46: }

16.

513

i j '

Int: 2

^ong. 30303
Double: 393939397834
Float: 3.33
Word: Hello
Unsigned: 85
Int: 2
Long: 30303
Double: 3.93939e+11
Float: 3.33
Word: Hello
Unsigned:

85

Int, Long, Double, Float, Word, Unsigned: 3 304938 393847473 6.66 bye -2
Int: 3
Long: 304938
Double: 3.93847e+08
Float: 6.66
Word: bye
Unsigned: 4294967294

.
,
.
34
,
. ein
, .
,
.
42, .
-2. ,
, -2
. cout
4294967294, -2.
, , ,
. ein
, 35-36.

istream
>> istream. ein
istream,
, :
Int VarOne, varTwo, varThree;
cout << "Enter three numbers: "
ein >> VarOne varTwo >> varThree;

514

ein VarOne varTwo varThree; ein


ist ream,
varTwo. :

VarOne,

((ein >> VarOne) >> varTwo) >> varThree;

cout, .

ein
ein
. ,
.


operator, ,
.
- get(). get()
, .

get(j
get () .
EOF (end of file
) . get() .
, cin.get()
, iostream.
:
cin.getO myVarOne >> myVarTwo //

cin.getO myVarOne int, iostream.


get() 16.4.

16.4. g e t ( ) ___________
1:. // 16.4. get()
2: include <iostream.h>

3:
4: int main()
5: {
6:

char ch;

7:

while ( (ch = cin.getO) != EOF)

8: {
9:

cout << "ch: " << ch endl;

10: }
11:
cout "\ nDone!\ n";
12: return 0;
13: }

16.

515


.
<+>, <11+0>.

Hello
ch

ch

ch

ch

ch

ch
World
ch

ch

ch

ch

ch

ch
(ctrl-z)
Done!

- 4 6 . while
, ein. get(), ch,
EOF, . EOF,
<Ctrl+Z> DOS <Ctrl+D> UNIX.
, ist ream
- get(), ANSI/ISO.

get()
get () ,
, .
iostream, ,
16.5.

16.5. g e t ( ) _____________________________
1: // 16.5. get()
2: include <iostream.h>

3:
4: int main()
5: {
6:

char a, b, c;

7:
8:

cout "Enter three letters:

9:
10:

516

cin.get(a).get(b).get(c);

11:
12:
cout "a: " a "\ nb: " b "\ nc: " << << endl;
13: return 0;
14: }

Enter three letters: one

'' 6 a, b . 10
'
cin.get().
cin.get(a),
cin, cin.get(b),
. cin. get (),
.
cin.getO cin, :
cin.get(a) b;

cin.get(a) cin,
: cin b;.

,
,
.

get
,
,
.


(),
get() getline().
get() .
,
,
, .
20, get() 19
, ,
.
( \ ). ,
,
,
.
16.6.

16.

517

IB.. g e t ( )
1:

// 16.6. get()c

2:

include <iostream.h>

3:
4:

int main()

5:

6:

char stringOne[256];

7:

char stringTwo[256];

8:
9:

cout << "Enter string one: ";

10:

cin.get(string0ne,256);

11:

cout << "stringOne: " << stringOne << endl;

12 :
13:

cout << "Enter string two:

14:

cin >> stringTwo:

15:

cout << "StringTwo: " << stringTwo endl;

16:

return 0;

17:

Enter string one: Now is the time


stringOne: Now is the time
Enter string two: For all good
StringTwo: For

6 7 . 9
, 10
cin.get() .
,
( \0 ). ,
.
Now is the time.
stringOne.
13,
. ,
, , , .

getline(), 16.7.

1.7. get l i n e ( )
1:

// 16.7. getline()

2:

include <iostream.h>

3:
4:

int main()

5:
6:

{
char string0ne[256];

7:

char stringTwo[256];

8:

char stringThree[256];

9:

518

cout "Enter string


. getl ine(string0ne
cout "stringOne:

one: ";

14

cout << "Enter string

two: ";

15

>> stringTwo;
cout
'stringTwo:

stringTwo << endl;

10
11
12

256);
stringOne << endl;

13

16
17

cout << "Enter string three: ";


. getl ine(stringThree,256);
cout << "stringThree:
<< stringThree << endl;
return 0;

18
19
20
21
22

Enter string one: one two three


stringOne: one two three
Enter string two: four five six
stringTwo: four
Enter string three: stringThree: five six

,
.
68 . 10
, getline().
get(), getlineO
. , get(), getlineO
. , get()
.
14 ,
. four five six,
four stringTwo. Enter
string three: getlineO. five six
, .
getlineO , 20 stringThree.
, getlineO
, 15,
>>
.
, - get .
.
ist ream. ,
get() ,
( ).
get () ,
,
. get() , ,
.

16.

519

- get line () : ,
.
get line () get(),
, .

cin.iynore()

(EOL) (EOF).
ignore(). :
. , ignore(80, \ )
80 , .
, ignore()
. ignoreO 16.8.

1.8. i g n o r e Q _____________________________________________
1: // 16.8. ignore()
2: include ciostream.h>

3
4

int main()

char

char stringTwo[255];

string0ne[255];

8
9:

cout "Enter string one:";

10

cin.get(string0ne,255);

11
12

cout << "String one: " stringOne << endl;

13

cout "Enter string two: ";

14

cin.getline(stringTwo,255);

15

cout "String two: " stringTwo << endl;

16
17
18

cout << "\ n\ nNow try again..,\ n";

19

cout "Enter string one: ";

20

cin.get(stringOne,255);

21
22

cout << "String one: " string0ne<< endl;

23

cin.ignore(255,'\ n);

24
25

cout << "Enter string two: ";

26

cin.get line(stringTwo,255);

27
28

cout << "String Two: " stringTwo endl;


return 0;

29

Enter string one: once upon a time


String one: once upon a time
Enter string two: String two:

520

Now try again...


Enter string one: once upon a time
String one: once upon a time
Enter string two: there was a
String Two: there was a

6 7 . 9
. once upon
time. <Enter>. 10
get(), stringOne
, .
13 ,
getlineO 14 ,
, .
19 .
ignoreO (.
16.8 23). , getlineO 26
, .

- () puback(]
! ,
. (), .
^ .
16.9.

16.9. peek( ) putback()


//

16.9.

2
3

include <iostream.h>

int main()

()

putback()

char ch;

cout << "enter a phrase:

while ( cin.get(ch) )

9:

10
11

if (ch == ! ' )

12

else

cin. putbackC $' );

13
14
15

cout << ch;


while (cin.peek() == '# )
cin.ignore(1, ' #' ) :

16
17

return 0;

18

enter

phrase:

Now!is#the!time#for!fun#!

Now$isthe$timefor$fun$

16.

521

6 ch, 7
.
,
(!) ($) (#).
while main() ,
( <Ctrl+C> Windows
<Ctrl+Z> <Ctrl+D> MS DOS UNIX ). ( ,
cin.getO 0 .)
, , putback() $.
, .
#, ignore().

( , # ,
). ,
putback() ignore(). , .

----

() 1()
. , ,
.

cout
cout
(<<) , .
,
. , .


, , , endl
. - flush() cout,
. flush(),
- flush(), :
cout << flush

,
.

- cout
, cin: get() getline(),
cout put() write().
put () .
ostream, a cout ostream,
put() ,
. 16.10.

522

IB. 10. p u t ( )
1:

// 16.10. put()

2:

include <iostream.h>

3:
4:

int main()

5
6
7

cout.put(H).put('e').put(1).put('1).put(o).put( \ n );
return 0;

Hello


Hello. ,
.

6 : cout. put (' ')


cout.
:
cout.put().put( ).put('1).put(o').put(\ n');

, cout.put('1'). ,
,
cout. ( \ ) .
write() , (),
, .
16.11.

1.11. w r i t e ( ) ______________________________________
1: // 16.11. write()
2: include <iostream.h>
3: include <string.h>
4
5

int main()

6
7

char One[] = "One if by land";

8
9:

10
11

int

12

int tooShort = fullLength -4

13

int tooLong = fullLength + 6

fullLength

strlen(One)

14
15

cout.write(0ne,fullLength) << "\ n";

16.

523

16:

cout.write(One.tooShort) "\ n";

17:

cout.write(One,tooLong) << "\ n";

18:

return 0;

19:

One if by land
One if by
One if by land i?!

7 .
11
fullLength. tooShort
, tooLong .
15 write() ,
.
16 , ,
.
17,
write() .
, , .

,
,
( ),
, .
,
.
21. ostream -
.

cout.width[]
,
.
width() .
cout, -.
width() .
16.12.

524

IB.12.
1:// 16.12.
2:

include <iostream.h>

3:
4:

int main()

5:
6:

{
cout "Start >";

7:

cout.width(25);

8:

cout << 123 "< End\ n";

9:
10:

cout << "Start >";

11:

cout.width(25);

12:

cout 123 "< Next >";

13:

cout << 456 << "< End\ n";

14:
15:

cout "Start >";

16:

cout.width(4);

17:

cout << 123456 << "< End\ n";

18:
19:

return 0;

20:

Start >

123< End
Start >

123< Next >456< End

Start >123456< End

( 68) 123 25
. 7.
.
123
25, 456. ,
, cout
. , width()
.
,
.
.


cout ,
width(), .
,
(). fi 11 (),
. fill()
16.13.

16.

525

16.13. f i i i ( )
1: // 16.13. fill()
2:
3: include <iostream.h>
4:
5: int main()

6: {
7:

cout << "Start >";

8:

cout.width(25);

9:

cout << 123 << "< End\ n";

10:
11:
12:

cout << "Start >";

13:

cout.widtb(25);

14:

cout.fill(*' );

15:

cout << 123 << "< End\ n";

16: return 0;
17: }

Start >

123< End

Start >******************123< End

7-9 .
1215, 14
fill(' *') (*) ,
.

iostream .
setf(),
.

,
.
,
( 20,00 20).
setf(ios: :showpoint).
iostream (ios),

ios: :, ios: :showpoint.
(+)
ios: :showpos.
, , ios:: left, ios:: right
ios::interval .
,
ios::dec ( ), ios: :oct ( )
ios: :hex ( ).
(). 16.4.

526

16.14. s e t f
1:

// 16.14. setf

2:

include <iostream.h>

include <iomanip.h>

4:
5:

int main()

6:

7:

const int number = 185;

8;

cout << "The number is " << number << endl;

9;
10:

cout << "The number is " << hex << number << endl;

11:
12:

cout.setf(ios::showbase);

13:

cout << "The number is " << hex << number << endl;

14:
15:

cout << "The number is " ;

16:

cout.width(IO);

17:

cout hex << number << endl;

18:
19:

cout << "The number is " ;

20:

cout.width(IO);

21:

cout.setf(ios::left);

22:

cout << hex number << endl;

23:
24:

cout << "The number is " ;

25:

cout.width(IO);

26:

cout.setf(ios::internal);

27:

cout hex << number << endl;

28:
29:cout << "The number is:" << setw(10) << hex << number << endl;
30:

return 0;

31:

'* * ^

The number is 185


The number is b9
The number is 0xb9
The number is

0xb9

The number is 0xb9


The number is Ox

b9

The number is:0x

b9

%, >

7 number 185,
8.
10, ,
hex, 9. ( b
11 . 11 16 176.
9, 185.)

16.

527

12 ^,
.
16 10.
. 20 10,
. .
25 10,
. , 9 .
, 29 ,
<( ) , ().
.


++
- , ^().
^) , , .
) ,
.
, ^) ,
.
pintf () .
,
,
. ^)
,
.

.. )
, .

. . 16.1
, %.

1.1. _______________________________________

%s

%d

integer

%1

long integer

%ld

double

%f

float


.
,

528

,
. , %51
5 , %15^
15 , .
^ 16.15.

16.15. 1 1 ( ) ___________________________
I:

include <stdio.h>

2:

int main()

3:

4:

printf("%s","hello world\ n");

5:
6:

char *phrase = "Hello again!\ n";

7:

printf(%s",phrase);

8:
9;

int x = 5;

10:

printf("%d\ n",x);

II :
12:
13:

char phraseTwo = "Heres some values: ";


char *phraseThree = " and also these: ";

14:

int y = 7, z = 35;

15:

long longVar = 98456;

16:

float floatVar = 8.8f;

17:
18:printf("%s %d %d %s %ld %f\ n",phraseTwo,y,z, phraseThree,longVar,floatVar);
19:
20:

char phraseFour = "Formatted: ";

21:printf("%s %5d %10d %10.5f\ n",phraseFour,y,z,floatVar);


22:

return 0;

23:

>

/ ~ ' hello world


Hello again!
5
Here's some values: 7 35 and also these: 98456 8.800000
Formatted:

35 8.800000

; ,t

printf 4
: printf
( %s) , .
%s , ,
, "hello world".
printf 7 ,
, , char.
printf() 10
, .
printf(), 18.
. ,
.

16.

529

, 21 printf()
,
. ,
printf () , cout.
printf()

.
.


C++
C++
, .
cout :
\ ;
\ ;
;\t ;
\\ ;
' \ddd ( ) ASCII;
\ ().
:
cout "\aAn error occured\t"
,

. cout .
iomanip.n.
,
iomanip.h:
flush ;
endl ;
oct ;
dec ;
f.tiex .
,
iomanip.h:
: setbase () (0 =
, 8 = , 10 = , 16 = );
' setw () ;
setfill () \
.-setprecision () ;
setiosflags () ;

530

resetiosflags () .
,

cout setw(12) setfill ( ' # ' ) hex x endl;


12 , #, , ,
. , flush,
endl setw, , ,
, . setw
cout.
;
setiosflags resetiosflags ios-:
; '
los: :left ; '
ios:: right ;
ios:.: interval ;
ios: :tiec ;
ios: :oct ;
!
ios: :hex ;
ios::showbase 0
;
ios::showpoint ;
ios: uppercase
;

ios:: showpos V ;
ios::scientific
;
ios::fixed
.
ins. h
.


C++ ,
, .
,
.
, if stream of stream.

ofsfream
, ,
ofst ream. iostream.
, of stream,
. of stream
fstream. h.

16.

531

fstream ^^. 1,
iostream.li.


iostream , .
,
TRUE FALSE: eof(), bad(), fail() good(). eof() TRUE,
iostream EOF (end of file ). bad()
TRUE . fail()
TRUE , bad(),
, . ,
good() TRUE, , .. .
FALSE.

-
myfile.cpp ofstream
, :
ofstream foutfmyfile.cpp");

,
, ifst ream:
ifstream fin("myfile.cpp");

, fout fin,
, cout cin .
, , close().
( ).
close(),
.

, -.
16.16.

16.1. ___________________________________
1:

include <fstream.h>

2:

int main()

3:

4:

char fileName[80];

5:

char buffer[255]; //

6:
7:

cout << "File name: ";


cin >> fileName;

8:
9:
10:

532

ofstream fout(fileName); //
fout << "This line written directly to the file...\ n";

11:

cout "Enter text for the file:

12:

cin.ignore(1,'\ n);

13:

cin.getline(buff,255); // , ,

14:

fout << buffer << "\ "; //

15:

fout.closeO;

//

// ,

16:
17:

ifstream fin(fileName); //

18:

cout << "Here's the contents of the file :\ n";

19:
20:

char ch;
while (fin.get(ch))

21 :

cout << ch:

22:
23:

cout "\ n***Enci of file contents.***\ n";

24:
25:

fin.close();

//

26: return 0;
27; }

' File : testl


i,n
Enter text for the file: This text is written to the file!
Heres the contents of the file:
This line written directly to the file...
This text is written to the file!
***End of file contents.***

4 , 5
- ,
. 6 ,
filename. 9 ofstream fout,
. .
, .
10 , 11
. ,
, 12,
13.
, 15 .
17 , ,
2021.

ofstream
ofstream
, ,
.
, ofstream.
:

ios : : ;

ios: :ate ,
;

16.

533

ios: :trunc ; ()
;

ios: :nocreate

ios:: noreplace

, ;
, .

: apend
(), ate at end ( ), trunc truncate () ..
16.17 16.16
.

16.17. ____________________________________
1: include <fstream.h>
2: int main() // 1

3: {
4:
5:
6:
7:
8:
9:
10:

char fileName[80]:
char butfer[255];
cout "Please re-enter the file name:
cin >> filename;

11:

12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:

ifstream fin(fileName);
if (fin)

// ?

cout << "Current file contents:\ n";


char ch;
while (fin.get(ch))
cout << ch;
cout \ n***End of file contents.***\ n";
}
fin.closeO;
cout "\ nOpening " filename " in append mode...\ n;
ofstream fout(fileName,ios::app);
if (!fout)
{
cout "Unable to open " << fileName " for appending.\ n";
return(1);
}

28:
29:
30:

cout << "\ nEnter text for the file: ";


cin.ignore(1,'\ n');

31:

cin.getline(buffer,255);

32:
33:
34:
35:
36:
37:
38:

fout buffer "\ n";


fout.close();

39:

534

fin.open(fileName); // fin!
if (!fin)
{
cout << "Unable to open " fileName << " for reading.\ n";

return(1);

40:
41:
42:
43:
44:
45:
46:
47:
48: }

}
cout << "\ nHere's the contents of the file:\ n";
char ch;
while (fin.get(ch))
cout << ch;
cout << "\ n***End of file contents.***\ n";
fin.closeO;
return 0;

Please re-enter the file name: testl


Current file contents:
This line written directly to the file...
This text is written to the file!
***End of file contents.***
Opening testl in append mode...
Enter text for the file: More text for the file!
Here's the contents of the file:
This line written directly to the file...
This text is written to the file!
More text for the .file!
***End of file contents.***

,
9
. 10
, ,
1216. , if(fin)
if(fin.goodO).
,
( 22). (, , )
. if(! fout)
if (fout.failQ). ,
33 .
, 16.16, ,
fin.
. 36
.


.

ifstream ofstream.
fstream
.

16.

535


, DOS,
. ( ASCII).
, 54321, ('57473','2','1').
,
DOS.
,
C++ ios::binary.
, .
!
,
. ,
write() fstream.
write(),
read(). -
,
.
.
sizeof(). ,
, . .
16.18 , ,

16.18.
include <fstream.h>

class Animal

4
5

public:
Animal(int
weight,
~Animal(){ }

6
7

long

days):itsWeight(weight),

itsNumberDaysAlive(days){

9:
10
11

int GetWeight()const { return itsWeight; }


void SetWeight(int weight) { itsWeight = weight; }

12

long
GetDaysAlive()const
{
return
itsNumberDaysAlive;
void SetDaysAlive(long days) { itsNumberDaysAlive = days; }

13
14
15

private :

16
17
18
19

20
21
22
23
24

536

int itsWeight;
long itsNumberDaysAlive

>;
int main() // returns 1 on error
char fileName[80];

25:
26:

cout "Please enter the file name:


cin fileName;

27:

ofstream fout(fileName,ios::binary);

28:
29:
30:
31:
32:
33:
34:
35:

if (!tout)
<
cout << "Unable to open " << fileName << " for writing.\ n";
return(1);
}
Animal Bear(50,100);
fout.write((char*) &Bear,sizeof Bear);

36:
37:
38:
39:

fout.closeO;

40:
41:

if (!fin)
{

42:
43:
44:
45:
46:
47:

ifstream fin(fileName,ios::binary);

cout << "Unable to open " << fileName << " for reading.\ n";
return(1);
>
Animal BearTwo(1,1);

48:
49:

cout << "BearTwo weight: " << BearTwo.GetWeight() << endl;


cout "BearTwo days: " << BearTwo.GetDaysAlive() endl;

50:
51:

fin.read((char*) &BearTwo, sizeof BearTwo);

52:
53:
54:

cout << "BearTwo weight: " << BearTwo.GetWeight() << endl;


cout << "BearTwo days: " << BearTwo.GetDaysAlive() endl;

55:
56:
57: >

fin.close();
return 0;

Please enter the file


BearTwo weight: 1
BearTwo days: 1
BearTwo weight: 50
BearTwo days: 100

name:

Animals

318 Animal. 2232 ,


. 34

Animal

-
itsWeight
=
50

itsNumberDaysAlive = 100. .
37 ,
39. Animal,
- 1. 51
Animal, .

16.

537

-

, DOS UNIX,
.
, ,
, :
SomeProgram Paraml Param2

main().
) .
,
. (
).
. ( SomeProgram
.)
, main(),
.
, char,
.
argc (argument count
), , .
argv (argument vector ),
.
, arge
, argv.
: argv[0] , a argv[1]
. ,
. 21 ,
,
. 16.19 .
main(

1 . 19. ____________________________
1:
2:

include <iostream.h>
int main(int arge, char **argv)

3:

4:
5:
6:
7:

cout << "Received " << arge << " arguments...\ n;


for (int i=0; i<argc; i++)
cout << "argument " << i << " << argv[i] << endl;
return 0;

8:

TestProgram Teach Yourself C++ In 21 Days


Received 7 arguments...
argument 0: TestProgram.exe
argument 1 : Teach

538

argument 2:
argument 3:

Yourself
C++

argument 4:

In

argument 5:
argument 6:

21
Days

,
(.
).

main() : arge
, , argv
.
. , argv char *argv[]
char[ ][]. , .
,

.
4 argv
. , .
5 6 for,
, argv
[i]. cout.
16.20 16.18,
.

16.20. _______________ ___________


1: include <fstream.h>
2:

3: class Animal
4: {
5: public:
6:
Animal(int weight, long days):itsWeight(weight), itsNumberDaysAlive(days){ }
7:
"Animal(){ }
8:

9:
10:

int GetWeight()const { return itsWeight; }


void SetWeight(int weight) { itsWeight = weight; }

11 :

12:
13:
14:
15:
16:
17:
18:
19:
20:
21:

long GetDaysAlive()const { return itsNumberDaysAlive; }


void SetDaysAlive(long days) { itsNumberDaysAlive = days; }
private:
int itsWeight;
long itsNumberDaysAlive;
} ;
int main(int argc, char *argv[]) // 1
{

16.

539

22:
23:
24:
25:
26: }
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58: }

if (argc != 2)
{
cout << "Usage: " << argv[0] " <filename>" << endl;
return(1);

ofstream fout(argv[1],ios::binary);
if (!fout)
{
cout << "Unable to open " << argv[1] " for writing.\ n";
return(1);
}
Animal Bear(50,100);
fout.write((char*) &Bear,sizeof Bear);
fout.close();
ifstream fin(argv[1],ios::binary);
if (!fin)
{
cout << "Unable to open " argv[1] << " for reading.\ n";
return(1);
}
Animal BearTwo(1,1);
cout << "BearTwo weight: " << BearTwo.GetWeight() << endl;
cout << "BearTwo days: " << BearTwo.GetDaysAlive() << endl;
fin.read((char*) &BearTwo, sizeof BearTwo);
cout << "BearTwo weight: " << BearTwo.GetWeight() << endl;
cout << "BearTwo days: " << BearTwo.Get0aysAlive() endl;
fin.close();
return 0;

BearTwo weight : 1
BearTwo days: 1
BearTwo

weight:

50

BearTwo days: 100

Animal 16.18.
,
. 2 main(),
:
, .

540

2226 ,
. , :
Usage TestProgram <>

. ,
, argv[0] .
,
.
28 .
, ,
16.18,
argv[1 ].
40,
, 25 31 .

cout ein.
ist ream ostream -.
: cout, ein, cerr
clog. .
ein ist ream
(). cout ostream
().
- -,
get() put(). ,
.
.
,
.
f st ream,
iostream. ,
read() write(),
.


, ,
- ?
,
. ,
(, ,
), .
cerr clog?
cerr ? , ,
cerr, .

16.

541

, .
clog ,
.
, printfO?
printfO ,
C++. , .
putbackQ?
,

, .

, .
ignoreO?
get ().
, get()
ignore( 1, \');. , putback(), , ,
.
C++ printfO.
?
, . , ,
.


,
.
, .
,
.


1. ?

2. ?
3. cin.getO
.
4.

cin.readO cin.getlineO?

5.
?
6. ?
7. of stream?
8. ios:: ate?

542

1. ,
iostream cin, cout, cerr clog.
2.

,
.

3.

ignore().

4.

,
.
, ,
( ).
.

5.

,
, .

16.

16.9,

putback()

543


ANSI C++
,
. :

std

- C++.
ANSI
(namespaces). ,
.
,
.
. ,
List. (
19)
List . ,
List
. List ,
. ,
- ,
List
, . *
,
, , .
, .

, . .

544

,
.
.

UMGH

. ,
, .

(, ). ,
.
Identifier multiply
defined ( ),
,
.
,
.
:
// fi.rsl.cpp
int lntagorValue = 0 ;
int maln( ) {
int IntegerValue = 0 ;

// . . .
return 0 ;

};
// second,epp
int integerValue = 0 ;
// second.epp

in

second.obj:

integerValue

already

defined

In

first, obj (IntegerValue second, ob] first, obj).


,
.
: identifier hiding (
). , first.
integerValue mai() .
main() integerVaalue,
main(),
(: :). , 10
integerValue,
, maln():
// first.epp
int integerValue - 0 ;
irit main( )

{
Int integerValue = 0 ;
integerValue = 10 ; // integerValue

17.

545

// . . .
return

};
// second.epp
int integerValue = 0
// second.epp

(: ),
^
, .

, , ,
.
, ,
, ,
. , ,
, ,
.
. , ,
, .
.
:
int globalScopelnt = 5 ;
void f( )

{
int localScopelnt = 10 ;

}
int main( )

{
int localScopelnt = 15 ;

{
int anotherLocal = 20 ;
int localScopelnt = 30 ;

}
return 0 ;

}
GlobalScopelnt
main (). f()
localScopelnt. , .. ,
.
main() localScopelnt f().
f(), localScopelnt
. , localScopelnt,
main(). .
f(),

546

: localScopelnt main()
f().
anotherLocal localScopelnt . ,
,
, .
, , ,
localScopelnt,
, . ,
. , ,
.
localScopelnt .
, localScopelnt ,
localScopelnt.
.

.
.
, , ,
,
.
.
.
// : first.
int externallnt = 5 ;
const int j = 10 ;
int main()

{
return 0 ;

}
// : second.
extern int externallnt ;
int anExternallnt = 10 ;
const int j = 10 :

externallnt, first., .
first , ,
second, . j,
.
, ,
:
// : first.
extern const int j = 10 ;
// : second.
extern const int ] ;
include <iostream>
int main()

17.

547

{
std::cout "j = " j sKJ: :imH ,
return 0 ;
>
std
cout, ANSI.
;
j 10

, :

staue

static int staticlnt - 10 ;


int main()
{
//...
}
static ,
.
static ,

811

.



. namespace ,
, .

. :
namespace Window

{
void nove( int x, int ) ;

}
Window .
,
.
C++.
.

548

std


. ,
:
// heade 1.h
namespace Window

{
void move( int x, int ) ;

}
// heador2.h
namespace Window

{
void resmi( int x, ini ) ;


.
C++.
,
.
, .
:
namespace Window {
// . . . ,
void move( int , int ) ; //
void resize( int x, int ) :
// . . . ,
void move( int , int )

{
if( < MAX_SCREEN_X && x > 0 )
if( < MAX_SCREEN_Y && > 0 )
platform.move( x, ) ; //

>
void resize( int x, int )

{
if( X

< MAX_SIZE__X && x > 0 )


< MAX_SIZE_Y 8 > 0 )
platform. resize( x ) : //

if(

}
// . . .

}
,
!
20 , ,
?

17.

549


.
,
. ,

, .
:
// header.h
namespace Window {
void move( int x, int y) ;
//

}
// file impl.cpp
void Window::move( int x, int )

{
//

>



.
, , .
. .
namespace Window {
//

}
//
int Window::newIntegerlnNamespace ; //

, .
, - newIntegerlnNamespace
.
.
:
namespace Window {
private:
void move( int x, int ) ;


.
,
.

550

,
. ,
:
namespace Window {
namespace Pane {
void size( int x, int ) ;

}
>
size() Window
,
, :
int main( )

{
Window::Pane::size( 10, 20 ) ;
return 0 ;



. Window
, -.
, ,
,
17.1.

17.1. _____________ _____________ _________


1: include <iostream>
2
3 namespace Window
4 {
5
const int MAX_X = 30 ;
6
const int MAX_Y = 40 ;
7
class Pane
8
<
9
public:
10
Pane() :
11
Pane() ;
12
void size( int
void move( int
13
14
void show( ) ;
15
private:
16
static int cnt
17
int x ;
18
int y ;
19
} :
20 >

17.

551

21:

22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:

int Window::Pane::cnt = 0 ;
Window::Pane::Pane() : x(0), y(0) { )
Window::Pane::"Pane() { }
void Window;'.Pane: :size( int x, int y )
{
if( x < Window::MAX^X && x > 0 )
Pane; : x = x :
if( y < Window::MAX_Y && y > 0 )
Pane::y = y ;
}
void Window: :Pane: :inove( int x, int y )
{
if( x < Window::MAX_X && x > 0 )
Pane::x = x ;
if( y < Window::MAX_Y && y > 0 )

38:
Pane::y = y ;
39: }
40: void Window::Pane::show( )
41: {
42: std::cout << "x " << Pane::x ;
43: std::cout << " y " << Pane::y << std::endl
44: }
45:
46: int main( )
47: {
48 : Window::Pane pane ;
49:
50: pane.move( 20, 20 ) ;
51: pane.show( ) ;
52:
53: return 0 ;
54: }

x 20 20

, Window.

Window: :.
- cnt, 16 ,
. - Pane::size()
- _ MAX_Y 2632
. , -
, - (
Pane: :move()) , .
.

552

, -
-
: : : : :. ? ,
, Pane: :move() :
void Window::Pane::move( int , int )

{
if( < Window::_ && x > 0 )
x = x ;
if( < Window: :MAX_Y && > 0 )
= ;
Platform::trrave( , ) ;

}
, , ? ,
.
.
- , ,
-
. ,
- :
:: = ;
:: = ;

using
Bin ,
, using
.

using
using
.
, . using
:
namespace Window {
int valuol - 20 ;
int value? = 40 ;

}
Window::valu1 = 10 ;
using namespace Window ;
value2 = 30 :

Window ,
Window; .
, value!

using

namespace

17.

553

,
value2, using
Window.
using
.
, ,
. :
namespace Window {
int valuel = 20 :
int value2 = 40 ;

>
//
void f()

{
{
using namespace Window ;
value2 = 30 :

}
value2 = 20 ; //!

}
f() value2 = 20
, value2 .
, using,
.

, , .

. , ,
using ,
. :
namespace Window {
int valuel = 20 ;
int value2 = 40 ;

>
//
void f()

<
int value2 = 10 ;
using namespace Window ;
std::cout << value2 << std::endl ;

}
10, 40,
, value2 Window
value2 f().
, .

554

,
, ,
. ,
, :
namespace Window {
int valuel = 20 ;

}
//. . .
using namespace Window ;
int valuel = 10 ;
void f( )

{
valuel = 10 ;

}
f().
Window:: valuel .
.
f()? ,
,
f ().

using

using
using

,
.
, , :
using

namespace Window {
int valuel = 20 ;
int value2 = 40 ;
int value3 = 60 ;

}
//
using Window::value2 ; // value2
Window::value1 = 10 ; // valuel
value2 = 30 ;
Window::value3 = 10 ; // value3

, using
,
, . value2
,
valuel value3. using
.
using ,
.
,
. using
, .

17.

555

, ,
,
.
, .
:
namespace Window {
int valuel = 20 :
int value2 = 40 ;

}
//
void f()

{
int value2 = 10 ;
using Window:: value2 ; //

std::cout << value2 << std::endl ;

}
f() ,
value2 . ,
using valuo2.
,
using, ,
. :
namespkoe Window {
Int valuel - 20 ;
int va]ue2 - 40 ;

}
int value2 = 10 ;

//.
void f()

{
using Window:: value?
8t(1 : :cout value? -'< hUI: :ciuil

}
using I ( )
value?.
,

. using
, .
using , ,
, .

. using
,
.

556



. ,
, .
, .
. :
namespace the_software_company {
int value ;

// .
}
the__software_company::value = 10 ;
namespace TSC = the_software_company ;
TSC::value = 20 ;

,
.
, .


, .

.
. , ,
- .
, .
// : one,
namespace {
int value ;
char p( char *p ) ;

//. . .
}
// : two.cpp
namespace {
int value ;
char p( char *p ) ;

//, . .
}
int nain( )

{
char = p( ptr ) ;

}
value ().
,

17.

557

. ().
,

static int value = 10 ;

, static
.
.
: .

std

C++. , ,
std.
, :
include <iostream>
using namespace std ;

He , using
.
. ?
, .

,
. ,
, ,
using, ,
, . ,
.
.
using, :
include <iostream>
using std::ein ;
using std::cout ;
using std::endl ;
int main( )

{
int value = 0 ;
cout << "So, how many eggs did you say you wanted?" << endl ;
ein >> value ;
cout value << " eggs, sunny-side up!" << endl ;
return( 0 ) ;

}
:
So, how many eggs did you say you wanted?
4
4 eggs, sunny-side up!

558

,
:
include <iostream>
int main( )

{
int value = 0 ;
std::cout << "How many eggs did you want?" << std::endl ;
std::cin value ;
std::cout << value << " eggs, sunny-side up!" << std::endl ;
return( 0 ) ;

}
:
How many eggs did you want?
4
4 eggs, sunny-side up!

,

. : std::
!

, .
, . -,
. -,
, . ,
.
, .
,
.
. .
. ,

.

using.
, .
,
.
using .
using

, .
typedef.
,
, .

17.

559

.
, .
namespace,
.
.
static.
C++ stci.
using,
. using.


?
, .
, (, include
<string. h>), (, include <cst ring. h>).
using?
using
.
. .
?
,
.
.

.


1. , ,
using?
2.
.
3. std?

1. : :
include <iostream>
int main()

{
cout << "Hello world!"
return 0;

end;

}
2. , 1.

560

++, ,
. :

,
-

()

++ -

++
.

.
, ,
, .
,
, .
, ,
. , ,
, .

18. - 561

, Internet,
,
.

.
.
, ,
.
. , .
.
, -
, .
-
, . ,
,
.
, ,
.
?
: , , , , .
: , , ,
, . , :
, , , , .
,
, ,
, .
, .


,
, .
.
, ,
.
. ;
,
, , .
, .
, , ..,
, , , ,
. , ,
.
, , .
(Steven Wright) : ,
. 5.
-
.
, -,
, -, .

562

:
, , ,
.
.
,

. Geranium (),
Flower (), . 18.1.

. 18.1.

, Geranium Flower,
.
, . ,
,
,
.
,
, .
, ,
, , ,
.
,
. (
, .)
, UML (Unified Modeling Language
). ,
.
UML , . 18.1,
(. 18.2).

18. - 563

. 18.2. , 11

UML
, ,
. ,
, : , .
UML .
.
, UML .
, , ,
UML :
, .

-
, .
.

UML,
.
: ,
! . ,
.
.
(Grady Booch), , (Ivor Ja
cobson),

-
,

(James Rumbnugh), .
Objectory Rational Software,
Inc. , ".
, , Objectory.
,
.
,
. Objectory ,
, .
. ,
,
, , ,
, .
.
,
.
,
(. 18.3).
,
, . , ,
. .
,
.
,
.

18. - 565

, ,
.
, ,
.
,
.

. 18.3.

,
- .
: , ,
, , ,
. ,
,
,
.
.
1. .
2. .
3. .
4. .
5. .
6. .

, ,
. .
, .
(, ++); ,
, ,
. .

. , ,
, .
. -

566


( , ).
, , ,
, .

,
, , . :
. : ,
, .

, , -
.
.
,
, , .
.
, -
- .
.
, ,
, ,
. ,
, .


, , .
,
.
, .
.
, . ,
, ,
. ,
.
.
.



.
, .
.

18. - 567


. ,
, ,
.

,
. .
, ,
.
, :

,
;


, ;

, .

,
-.

.
. ,
.


, . ,
, .
,
(, ),
, ,
.
:

.
, :
, .
, , ,
: , , ..
.

:

,
.

568


.
. -
.
.


. ,
.

, .

, ,
, :
, ?
.
;
, , (
) (
-). :

.
, -
, .
,
.
,
, .

?
, .

?
, .

?
, .

, ?
.
! , .

?
.

18. - 569

!
.

. .

,
. ,
.
? , .
?
, ,

. ATM
:

ATM .

ATM .


,
.
, , (
). ,
,
.
: , , ,
, ..
:
(, , ..), ,
.
. . 18.4 ,
Rational Rose.

570

, ,
, .
.

# jCuJtomer
Vmt.,

ISP* ' jo*


&*{(

Pabfc .

' '3 :

The customer is any patron /the bank who has one * {


(ftcneaccourtt Thecustomuses<teATMtodepos*
morwy. tianif between accounts, check his balance and
to get cash.

J
j * I tv'A I Ap' j gtowse * j : Hdp
Puc. 18.4. Rational Rose

UML,
, ,
.
UML: .
, ,
. , UML
(. 18.5).
, ,
, , ,
. , C++ ,

.

. 18.5. ,

,
.
, .

18. - 571

,
. , ,
,
1 ( ) ( ),
,
. ,
.

,
. ,
.
, .
, . ,
.

. ,
, , , .. ,
, .. ,
, , .
,
, (. 18.6).

. 18.6.

572

. 18.7.

, 18.6 ,
.
, (, 18,7).
. 18.7 ,
,
.


, "

. ,
, ,
. I
(, 18,8),

. 18.8 ,
.

,
,
.
.
,
. , ,
, .

$300 ,
.

$300 ,
$200. ,
.

$300 ,
$100, $300. ,
$200.

$300 ,
.
, .

18. - 573

.
.
( ,
..). ,
. , .
,
,
, .


,
,
.
, .
, .
, .
.
, .
.
.
.
.
,
, .

:
:

:
:


. .

; .
.
, $300.

,
. 18.9.
.
.
,

574

. :
,
. , .
. 18.10.

. 18.9. - . 18.10.

. 18.10 ,
. ,
, ..
.
-
,
. ,
,
, ,
. ,
.
,
.



, ,
. , ,

, , .
, . 18.11.
,
. .
.

.

18. - 575

G^

1.
2.
3.
4. ,
.
S,
, $300
7,
8.
9.

, 18.! I.

,
,
.


-
,
. UML
.
.
(, ..).
,
. ,
( )
.
,
.



,
.

576


, .
, ,
, .

, .
, ,
.
,
,
. , .
,
.

, .


,
, .
,
.
, .
, , ?

?
?
,
. ,
,
. ,
..


- ,
, .
: 18 .
, . ,
,
. ,
.
.

, ,
, , , , .

, , ,
.
, .

, . ,

, - , .

18. - 577

, , ,
. , , , .
, . ,
, .
, , ,
.
. 20 25%
, . ,
.
,
. ,
,
.
, ,
,
.

.
, , ,
, ,
.

, ,
.
, ,
.

,
. . 18.1.

.
,
,
.

18.1. , ____________________________
_______________________________

578


, , ,


,

. 10.1


,
.
.
.
:
. , , (
, ) (
) .

, ,
.
,
.


,
C++.
, ,
C++, , , .
,
.
, C++
.
, ,
(), Cat

18. - 579

Meow(), -. ,
,
. UML,
C++ , .

,
.
.
(),
. .

.
, ATM
, . ATM
, $300.
.
:

ATM;

( );

ATM ( );

.
, . 18.12.

580

. 18.12.


.
. ,
, , ,
, .
, ..
--. ,
, .
.
: . 18.12 ,
. , ,
,
. 18.12.
. ,
, ,
.



. .
()
. (,
, ,

18. - 581

.
.)
, .

.
,
.
, .


.
(,
),
.
In
ternet. , ,
, .

, ( )
. ,
, .

(
, , ..),
. ,
, , .


,
.
, .
, ,
.
:
, . (
) .
,
.
, .
.
, .. .
,

. ,

582

. , ,
.
,
CRC.

CRC
CRC Class (), Responsibility (), Collaboration (
). CRC ,
. , ,
, ,
,
.


.
, . ,
,
. ,
( ).
, .
,
- .
, ,
.
( ), .
.
, ,
, .
CRC , ,
.
. ,
, , .
.
.
, () ,
.
: , .



. ,
.
,
.
,
. ,
, . ,
,
.

18. - 583

,

. , .


CRC ,
, .. . ,
.
CRC .
, .
.
, ATM
, . ATM
, $300.
.
, : ,
- ;
; ; ;
.
CRC : ,
. $300.
, $300 .
: ; $300 ,
$300. ,
$300 ? ? : ,
. : .
, ; . :
. - . ,
. ,
, ,
.
. ,
, .
. ,
.

CRC
CRC ,
. ,
. .
. ,
, .
, , ,
. ,
, . ,
,
, .
, CRC ,
UML. UML
. .

584

UML CRC
.
.
.
. . 18.13
,
, .

. 18.13. CRC

:
:
:





:



UML,
. .

18. - 585

C++ .
, :
.
,
.
, .
, ,
,
TransferFunds(). ,
.
, C++, Java,
( Java ,
, ).
, -
.
, ,
. ,
,
() .
,
.


?
, , , ,
. 18.14?

. 18.14. ,

:
, .. ,
.
(, ),
(. 18.15).

586

. 18.15 , ,
. .
, . ,
, .
.
, ,
, , .

. 18.15.

. 18.16 . ,
( )
, , (, )
. ,
.

. 18.16.

u

? , Acme Motors,
: Pluto ( ),

18. - 587

Venus ( ), Mars (
,
), Jupiter (-
, , , ) Earth (,
).
,
. 18.17.

. 18.17.

. ,
, .
, .
,
, .
(. . 18.17).

. 18.18.

. 18.18 ,
, ,
, .
.
, :
enum BodyType={sedan, coupe, minivan, stationwagon}

588

, .
, .
,
.
, ,
, performance,
, . UML ,

( ) ,
(,
), .
(performance) .
,
, . 18.19.
,
.
, .
C++
. , (
) PerformanceCharacteristics (. 18.20).
,
(body) (engine).
Class Car : public Vehicle

{
public:
Car();
-Car();
//
private:
PerformanceCharacteristics*pPerformance;

>;
,
.

,
. ,
, .
, ,
.


,
. , , ATM
.
, (. . 18.11),
,
. 18.21.

18. - 589

. 18.19.

. 18.20.

--- 1--1.

2.

3.

4.)
5.

. 18.21.


. ,

,
.

18. - 591

. . 18.21
. , ,
. 18.22 .
,
.
. , Rational Rose,
.

. 18.22.


,
.
(
). . 18.23
.

. ,
,
, .

.
, .

(. 18.24).
, , ,
.
, ,
.
, (. 18.25).
. 18.25 , . 18.24,
.
. ,
.

592

= start

. 18.23. - . 18.24.

. 18.25.

18. - 593



- .
,
.

. ,
,
.
.

.
, - .


-
?
-
, .
-
, ,
.
. , Pascal
, C++ .

- -,
?
, .
- ,
,
.

C++ - ?
C++, -
, .
, . ,
C++
- . ,
, 90- C++.
. , C++ ,
, , - , C++
, Microsoft.

594



, ,
. ,
.
,
.


1.

-
?

2. - ?
3. ?

1.

, ,
. ,
,
.

2. ?
3.

1. , :
, ; ,
; , -,
.

4. : , ,
, , .
5. , , ,
.
6. ?
7.

,

. .

8.

,
3, .

18. - 595


, C++,
, .
, (Standard Template Library
STL) C++.
, :

(STL)


,
PartsList PartsCatalog.
PartsList, , , ,
: PartsList .
, List
PartsList CatsList.
PartsList CatsList. ,
,
.
, . -
List . ,
, , ,
, ,
.
, , ANSI
C++,
.

596



, : PartsList , CatsList
. .
.
C++ .
List,
, ,
Animals.
, ,
. ,
, , ..
, ,
, , ;
STL,
.


(instantiation)
. .
(parameterized templates)

.

Array

( )

1: template <class > //


2: class Array
//

3: {
4: public:
5: ArrayO;
6: //
7: > I

template
. template.
, . ,
,
. ,
Animals.
class,
. , .
,
. T
int, Cat.

19.

597

Array

int

Cat,

Array<int> anlntArray;
Array<Cat> aCatArray;

anlntArray , aCatArray
Cat. Array<int>
, -
, .. 19.1
Array.

19.1 !

19.1. Array
1: // 19.1.
2:
include <iostream.h>
3:

const int DefaultSize = 10;

4:
5: template <class T> //
6:

class Array //

7:

8:

public:

9:
10:

//
Array(int itsSize = DefaultSize);

11:

Array(const Array &rhs);

12:

'ArrayO { delete [] pType; >

13:
14:

//

15:

Array& operator=(const Array&);

16:T& operator[](int offSet) < return pType[offSet]; >


17:
18:

//

19:

int getSize() { return itsSize; }

20:
21:

private:

22:

T *pType;

23:

int itsSize;

24:

} ;

. .
5 template,
.
class,
.

598

6 ( 24)
.
, , ,
. , , operator[]
,
.
,
integer.
Animal Animal.


Array .
<>. ,
, :
template <class >
Array<T>::Array(int size):
itsSize = size

{
pType = new T[size];
for (int i = 0; i<size; i++)
pType[i] = 0;

>
, ,
(class ).
<>, -
Array(int size).

,
.
.


Array -
, (operator) .. 19.2
, .


. ANSI C++,

.
, ,
. ,

.

19.

599

18.Z. ____________
1:

include <iostream.h>

2:
3:

const int DefaultSize = 10;

4:
5:
6;

// Animal
//

7:
8:

class Animal

9:
10:

{
public:

11:

Animal(int);

12:

Animal();

13:

'AnimalQ { }

14:

int GetWeightO const { return itsWeight; }

15:

void DisplayO const { cout << itsWeight; }

16:

private:

17:
18:
19:

int itsWeight;
} ;

20:

Animal::Animal(int weight):

21:

itsWeight(weight)

22:

{ >

23:

24:

Animal::Animal():

25:

itsWeight(O)

26:
27:

{ }

28:
29;

template <class T> //

30:

class Array //

31:

<

32;

public:

33:

//

34:

Array(int itsSize - DefaultSize);

35:
36:

Array(const Array &rhs);


'ArrayO { delete [] pType; >

37:
38:

//

39:

Array& operator=(const Array&);

40: T& operator[](int offSet) { return pType[offSet]; }


41:

const T& operator[](int offSet) const

42:

{ return pTypefoffSet]; }

43:

//

44:

int GetSizeO const { return itsSize; }

45:
46:

private:

47:

T *pType;

48:

int itsSize;

49:

> ;

600

50:
51:

// ...

52:
53:

//

54:

template <class >

55:

Array<T>::Array(int size):

56:
57:

itsSize(size)
{

58:
59:

pType = new T[size];


for (int i = 0; i<size; i++)

60:

pType[i] = 0;

61:

>

62:
63:

// -

64:

template <class T>

65:

Array<T>::Array(const Array &rhs)

66:
67:

{
itsSize = rhs.GetSize();

68:

pType = new T[itsSize];

69:

for (int i = 0; i<itsSize; i++)

70:

pType[i] = rhs[i];

71:

72:
73:

//

74:

template <class T>

75:Array<T>& Array<T>::operator=(const Array &rhs)


76:

77:

if (this == &rhs)

78:

return *this;

79:

delete [] pType;

80:

itsSize = rhs.GetSize();

81:

pType = new T[itsSize];

82:
83:
84:

for (int i = 0; i<itsSize; i++)


pType[i] = rhs[i];
return this;

85:

86:
87:

//

88:

int main()

89:

<

90:

Array<int> theArray; //

91: Array<Animal> the2oo; //


92:

Animal *pAnimal;

93:
94:

//

95: for(int i = 0; i < theArray.GetSizeO; i++)


96:

97:

theArray[i] = i*2;

98:

pAnimal = new Animal(i*3);

99:

theZoo[i] = *pAnimal;

19.

100:

delete pAnimal;

101:

102:

//

103:

for (int j = 0; j < theArray.GetSize(); j++)

104:

105:

cout "theArrayf << j "]:\ t";

106:
107:

cout theArray[j] << "\ t\ t";


cout "theZoo[" << j "]:\ t";

108:

theZoo[j].Display();

109:

cout endl;

110 :

111:
112:

return 0;

113: >

theArray[0]

theZoo[0]

theAr[1]

theZoo[1]

theArray[2]

theZoo[2]

- 6

theArray[3]
theArray[4]

theZoo[3]
theZoo[4]

9
12

theArray[5]
theArray[6]

10
12

theZoo[5]

15

theZoo[6]

18

theArray[7]

14

theZoo[7]

21

theArray[8]

16

theZoo[8]

theArray[9]

18

theZoo[9]

24
27

826 Animal, .
29 ,
, , .
Array ,
DefaultSize.
,
.
GetSizeO, .
, , .

. , ,
, ..
STL, .
-
, .


,
, . , SomeFunctionQ
, :
void SomeFunction(Array<int>&); //

602


void SomeFunction(Array<T>&); // !

, , &.
void SomeFunction(Array &); // !

, Array
.
,
, :
template Cclass >
void MyTemplateFunction(Array<T>&); //

MyTemplateFunction() ,
. , , ,
.
, , ,
. :
template cclass >
void MyOtherFunction(Array<T>&, Array<int>&); //

, :
. ,
.

, ;

, ;

,
.

,
,
. :
, -
. 19.3 Array
IntrudeO, ,
. Intrude-
Array.
, (
).

19.

603

18.3. -,
1:// 19.3. -

2:
3:
4:

include <iostream.h>

5:

const int DefaultSize = 10;

6:
7:

// Animal,

8:

//

9:
10:

class Animal

11:
12:

public:

13:

Animal(int);

14:

AnimalO;

15:

'AnimalO { >

16:

int GetWeight() const { return itsWeight; }

17:

void DisplayO const { cout itsWeight; >

18:
19:

private:
int itsWeight;

20:
21:

>;

22:

Animal::Animal(int weight):

23:

itsWeight(weight)

24:

{ }

25:
26:

Animal::Animal():

27:

itsWeight(O)

28:

{ >

29:
30:

template <class T> //

31:

class Array //

32:

33:
34:

public:
//

35:

Array(int itsSize = DefaultSize);

36:

Array(const Array &rhs);

37:

"ArrayO { delete [] pType; >

38:
39:

//

40:

Array& operator=(const Array&);

41: T& operator[](int offSet) { return pType[offSet]; }


42;

const T& operator[](int offSet) const

43:

{ return pType[offSet]; >

44:

//

45;

int GetSizeO const < return itsSize; }

46:
47:

// -

48:

friend void Intrude(Array<int>);

604

49:

50:

private:

51:

T *pType;

52:

int itsSize;

53:
} ;
54:
55:// - ,
56:// ! .
57:

void Intrude(Array<int> theArray)

.58:

59:

cout "\ n*** Intrude ***\ n";

60:

for (int i = 0; i < theArray.itsSize; i++)

61:

cout "i: " theArray.pTypefi] endl;

62:

cout << "\ n";

63:

64:
65:

// ...

66:
67:
68:

//
template <class T>

69:

Array<T>::Array(int size):

70:

itsSize(size)

71:
72:

{
pType = new T[size];

73:

for (int i = 0; i<size; i++)

74:

pType[i] = 0;

75:

76:
77:

// -

78:

template <class T>

79:

Array<T>::Array(const Array &rhs)

80:
81:
82:

<
itsSize = rhs.GetSize();
pType = new T[itsSize];

83:

for (int i = 0; i<itsSize; i++)

84:
85:

pType[i] = rhs[i];
}

86:
87:

// ( = )

88:

template <class T>

89: Array<T>& Array<T>::operator=(const Array &rhs)


90:

91:

if (this == &rhs)

92:

return *this;

93:

delete [] pType;

94:

itsSize = rhs.GetSize();

95:

pType = new T[itsSize];

96:

for (int i = 0; i<itsSize; i++)

97:
98:

pType[i] = rhs[i];
return this;

19.

605

99: >

100:
101: //
102: int main()
103: {
104:
105:

Array<int> theArray;
//
Array<Animal> theZoo; //

106:

Animal *pAnimal;

107:
108:

//

109:

for (int i = 0; i < theArray.GetSize(); i++)

110: {
111:

theArray[i] = i *2;

112:

pAnimal = new Animal(i*3);

113:

theZoo[i] = *pAniraal;

114:

115:
116:

int j;

117:

for (j = 0; j < theArray.GetSizeO; j++)

118: {
119:

cout "theZoo[" j "]:\ t";

120:

theZoo[j].Display();

121:

cout << endl;

122 : }
123:

cout "Now use the friend function to";

124:

cout "find the members of Array<int>";

125:

Intrude(theArray);

126:
127:

cout "\ n\ nDone.\ n";

128:

return 0;

129: >

theZoo[0]:

theZoo[1]:

theZoo[2]:

theZoo[3]:

theZoo[4]:

12

theZoo[5]:

15

theZoo[6]:

18

theZoo[7]:

21

theZoo[8]:

24

theZoo[9]: 27
Now use the friend function to find the members of Array<int>
*** Intrude ***
i: 0
i: 2
i: 4
i: 6
i: 8

606

: 14
: 16
: 18
Done.

Array
IntrudeQ. ,
int IntrudeO ,
, - -
.
60 IntrudeO itsSize,
61 - .
- , Array
.
, - .


Array .
,
Array .
. ,
.
ostream& operator<< (ost&, Array<T>&);

,
:

operator,

template <class > ostream& operator (ostream&, Array<T>&)

operator
. 19.4 Array,
operator.

18.4. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1:

include <iostream.h>

2:
3:

const int DefaultSize = 10;

4:
5:

class Animal

6:

7:
8:

public:
Animal(int);

9:

Animal();

10:

"AnimalO { }

11:

int GetWeightO const { return itsWeight; }

12:

void DisplayO const { cout << itsWeight; }

19.

13:
14:

private:
int itsWeight;

15:

};

16:
17:
18:
19:

Animal::Animal(int weight):
itsWeight(weight)

{}

20:
21:

Animal::Animal():

22:

itsWeight(O)

23:

{>

24:
25:

template <class T> //

26:

class Array

27:

28:

public:

//

//

29:
30:

Array(int itsSize = DefaultSize);

31:
32:

Array(const Array &rhs);


"ArrayO < delete [] pType; }

33:
34:

//

35:

Array& operator=(const Array&);

36:

T& operator[](int offSet) { return pType[offSet]; }

37:

const T& operatort](int offSet) const

38:

{ return pType[offSet]; }

39:

//

40:

int GetSizeO const { return itsSize; }

41:
friend ostream& operator<< (ostreamA, Array<T>&);

42:
43:
44:
45:

private:
T pType;

46:
47:

>;

int itsSize;

48:
49:
50:

template <class T>


ostream& operator<< (ostream& output, Array<T>& theArray)

51:

{
for (int i = 0; i<theArray.GetSize(); i++)

52:

output "[" i "] " theArray[i] endl; return output;

53:
54:

55:
56:

// . . .

57:
58:

//

59:

template <class T>

60:

Array<T>::Array(int size):

61:

itsSize(size)

62:

63:

= new T[size];

64:

for (int = 0; i<size; ++)

65:

pType[] = 0;

66: >
67:
68: // -
69: template <class T>
70: Array<T>::Array(const Array &rhs)

71: {
72: ItsSize = rhs.GetSizeO;
73:
pType = new T[ItsSize];
74:

for (Int 1 = 0; KltsSize; 1++)

75:

pType[i] = rhs[i];

76: }
77;
78: // (=)
79: template <class T>
80: Array<T>& Array<T>::operator=(const Array &rhs)
81: {
82:

if (this == &rhs)

83:

return this;

84:

delete [] pType;

85:

itsSize = rhs.GetSizeO;

86:

pType = new T[itsSize];

87:

for (int = 0; KitsSize; i++)

88:
89:

pType[i] = rhs[ ];
return *this;

90: >
91:
92: int main()
93: {
94:

bool Stop = false;

95:

int offset, value;

96:

Array<int> theArray;

//

97:
98:

while (!Stop)

99:

100:

cout << "Enter an offset (0-9) ";

101:

cout << "and a value. (-1 to stop): " ;

102:

cin >> offset value;

103:
104:
105:

if (offset < 0)
break;

106:
107:

if (offset > 9)

108: {
109:

cout "***Please use values between 0 and 9.***\ n";

110:

continue;

111: }
112:

19.

609

113:
114:

theArray[offset] = value;
}

115:
116:

cout << "\ nHere's the entire array:\ n";

117:

cout << theArray << endl;

118: return 0;
119: }

Enter an offset

(0-9

and a value.

Enter an offset

(0-9

and a value.

Enter an offset

(0-9

and a value.

Enter an offset

(0-9

and a value.

Enter an offset

(0-9

and a value.

Enter an offset
Enter an offset

(0-9

and a value.

(0-9

and a value.

Enter an offset

(0-9

and a value.

Enter an offset
Enter an offset

(0-9

and a value.

(0-9

and a value.

Please use values


Enter an offset

between 0 and

(0-9

and a value.

(-1 to stop)
(-1 to stop)

2 20

(-1 to stop)
(-1 to stop)

4 40

(-1 to stop)
(-1 to stop)

6 60

(-1 to stop)
(-1 to stop)
(-1 to stop)

1 10
3 30
5 50
7 70
8 80
9 90

(-1 to stop)
9. *.

1C 10

(-1 to stop)

-1 -1

Heres the entire array:

[0] 0
[1]

[2] 20
[3] 30
[4] 40
[5] 50
[6] 60
[7] 70
[8] 80
[9] 90

42 operator<<()
Array. operator<<()
,
operator() .
49.
. , operator()
, .


,
.
( ).
19.5.

610

19.5.
1: include <iostream.h>

2:
3: const int DefaultSize = 10;
4;
5: // ,
6; class Animal
7: {
8; public:
9: //
10:

Animal(int);

11:

Animal();

12:

"AnimalO;

13:
14:

//

15:

int GetWeight() const { return itsWeight; }

16:
17:

void SetWeight(int theWeight) { itsWeight = theWeight; }

18:

//

19:

friend ostream& operator<< (ostream&, const Animal&);

20:
21: private:
22:
23: } ;
24:

int itsWeight;

25: // Animal
26: ostream& operator
27:

(ostream& theStream, const Animal& theAnimal)

28 {
29: theStream << theAnimal.GetWeight();
30: return theStream;
31: >
32:
33: Animal::Animal(int weight):
34: itsWeight(weight)
35: {
36:
37: }

// cout << "Animal(int)\ n";

38:
39: Animal::Animal():

40: itsWeight(O)
41: {
42:

// cout << "Animal()\ n;

43: }
44:
45: Animal: :'AnimalO
46: {
47:

// cout << "Destroyed an animal...\ n";

48: }

19.

611

49:
50:
51:
52:
53:
54:
55:
56:
57:
56:
59:
60:
61:
62:
63
64:
65:

template <class T> //


class Array
//

{
public:
Array(int itsSize = DefaultSize);
Array(const Array &rhs);
"ArrayO { delete [] pType; }
Array& operator=(const Array&);
T& operator[](int offSet) { return pType[offSet]; )
const T& operator[](int offSet) const
{ return pType[offSet]; }
int GetSizeO const { return itsSize; }
// -
friend ostreami operator (ostream&, const Array<T>&);

66:
67:

68:
69:
70:
71:
70:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:

private:
T *pType;
int itsSize;

> ;
template cclass T>
ostreami operator (ostream& output, const Array<T>& theArray)

{
for (int i = 0; ictheArray.GetSizeO; i++)
output "[" i "] " theArray[i] endl;
return output;

>
// ...
//
template cclass T>
Array<T>::Array(int size):
itsSize(size)

86:

pType = new T[size];


for (int i = 0; i<size; i++)
pType[i] = 0;

87:
88:

89:
90:
91:
92:
93:

// -

94:

<

95:
96:
97:

template class T>


Array<T>::Array(const Array &rhs)
itsSize = rhs.GetSizeO;
pType = new T[itsSize];
for (int i = 0; KitsSize; i++)

98:

pType[i] = rhs[i];

99: }
100:
101: void IntFillFunction(Array<int>& theArray);
102: void AnimalFillFunction(Array<Animal>& theArray);
103:
104: int main()
105: <
106:
107:

Array<int> intArray;
Array<Animal> animalArray;

108:

IntFillFunction(intArray);

109:

Animal Fill Function(animalArray);

110:

cout "intArray.. n" intArray;

111:

cout << "\ nanimalArray...\ n" << animalArray << endl;

112:

return 0;

113: >
114:
115: void IntFillFunction(Array<int>& theArray)
116: {
117:

bool Stop = false;

118:

int offset, value;

119:
120 : {

while (!Stop)

121:

cout << "Enter an offset (0-9) ";

122:

cout "and a value, (-1 to stop): " ;

123:

cin offset value;

124:
125:
126:
127:
128:
129:
130:
131:

if (offset < 0)
break;
if (offset > 9)
<
cout "***Please use values between 0 and 9.***\ n";
continue;
}
theArray[offset] = value;

132: }
133: }
134:
135:
136: void AnimalFillFunction(Array<Animal>& theArray)
137: {
138: Animal * pAnimal;
139: for (int i = 0; KtheArray,GetSize(); i++)
140: {
141:

pAnimal = new Animal;

142:

pAnimal->SetWeight(i*100);

143:
144:

t h eA a [i] = *pAnimal;
delete pAnimal; //

145: }
146: >

19.

613

1 10

Enter an offset

(0-9) and a value.

-1 to stop)

Enter an offset

(0-9) and a value.

-1 to stop)

2 20

Enter an offset

(0-9) and a value.

-1 to stop)

3 30
4 40

Enter an offset
Enter an offset

(0-9) and a value.

-1 to stop)
-1 to stop)

5 50

Enter an offset
Enter an offset

(0-9) and a value.


(0-9) and a value.
(0-9) and a value.

-1 to stop)
-1 to stop)

6 60
7 70

Enter an offset

(0-9) and a value.

-1 to stop)

8 80

Enter an offset

(0-9) and a value.

-1 to stop)

9 90

Enter an offset

(0-9) and a value.

-1 to stop)
* * *

1C 10

(0-9) and a value. ( -1 to stop)

-1 -1

***Please use values


Enter an offset

between 0 and S

intArray:...

[0] 0
[1]

[2]

20

[3]

30

[4]

40

[5]

50

[6]

60

[7]

70

[8]

80

[9] 90

animalArray :...
[0]

[1]
[2]

200

[3]

300

[4]

400

[5]

500

[6]

600

[7]

700

100

[8]

800

[9]

900

Array
. Animal 623.
,
(), Animal.
, Animal
( , ).
,
.
, .
101 IntFill Function( ),
. ,
, .

614

102 AnimalFillFunction(),
Animal.
-,
Animal.



Animal (. 19.5), ,
Animal , .
.
Array
, 59 60 19.2.
someAnimal = (Animal) 0; operator=
Animal. Animal
, ().
, .
, Animal
. ,

. ,
Animal.
19.6 Animal.

13.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: include <iostream.h>

2
3

const int DefaultSize = 3;

4
5

// ,
class Animal

public :

9:

//

10
11
12

Animal(int);
Animal();
'Animal( ) ;

13
14

//

15

int GetWeight() const { return itsWeight; }

16

void SetWeight(int theWeight) { itsWeight = theWeight; }

17
18

//

19

friend ostream& operator (ostream&, const Animal&);

20
21

private :

22
23

int itsWeight;

};

24

19.

615

// Animal
ostream& operator
(ostreami theStream, const Animal& theAnimal)

25:
26:
27:
28:

{
theStream theAnimal.GetWeightO;
return theStream;

29:

30:
31:
32:

33:

Animal::Animal(int weight):
itsWeight(weight)

34:
35:
36:
37:
38:

{
cout "animal(int)

>
Animal::Animal():
itsWeight(O)

39:

40:
41:

<

42:

cout "animalO

43:
44:
45:

}
Animal:: 'AnimalO

46:
47:

48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
62:
63:
64:
65:

>

66:
67:

cout "Destroyed an animal...";

template <class T> //


class Array
//

{
public:
Array(int itsSize = DefaultSize);
Array(const Array &rhs);
'ArrayO ( delete [] pType; }
//
Array& operator=(const Array&);
T& operator[](int offSet) { return pType[offSet]; >
const T& operator[](int offSet) const
{ return pType[offSet]; }
//
int GetSizeO const { return itsSize; }
// -
friend ostream& operator (ostream&, const Array<T>&);

68:
69:

70:
71:
72:
73:

private:
T *pType;
int itsSize;

>;

74: template <class T>


75: Array<T>::Array(int size = DefaultSize):
76: itsSize(size)
77: {
78:
pType = new T[size];
79:
for (int i = 0; Ksize: i++)
80:
pType[i] = (T)0;
81: }

82:
83: template <class T>
84: Array<T>& Array<T>::operator=(const Array &rhs)
85: {
86:
if (this == &rhs)
87:
return this;
88:
delete [] pType;
89:
itsSize = rhs.GetSize();
90:
pType = new T[itsSize];
91:
for (int i = 0; i<itsSize; i++)
92:
pType[i] = rhs[i];
93:
return *this;
94: >
95: template <class T>
96: Array<T>::Array(const Array &rhs)
97: {
98: itsSize = rhs.GetSizeQ;
99:
pType = new T[itsSize];
100: for (int i = 0; icitsSize; i++)
101:
pType[i] = rhs[i];
102: }

103:

104:
105: template cclass T>
106: ostream& operator (ostream& output, const Array<T>& theArray)
107: {
108: for (int i = 0; i<theArray.GetSize(); i++)
109:
output "[" i "] " theArray[i] endl;
110: return output;
111; }

112:
113;

114; Array<Animal>::Array(int AnimalArraySize):


115; itsSize(AnimalArraySize)
116: {
117; pType = new Animal[AnimalArraySize];
118; }
119:
120;
121: void IntFillFunction(Array<int>& theArray);
122: void AnimalFillFunction(Array<Animal>& theArray);
123:

19.

124: int main()


125: {
126: Array<int> intArray;
127: Array<Animal> animalArray;
128:

IntFillFunction(intArray);

129:

Animal Fill Function(animalArray);

130: cout << "intArray...\ n" intArray;


131: cout "\ nanimalArray...\ n" << animalArray << endl;
132: return 0;
133: }
134:
135: void IntFillFunction(Array<int>& theArray)
136: {
137:

bool Stop = false;

138: int offset, value;


139: while (!Stop)
140:
141:

{
cout << "Enter an offset (0-9) and a value. ";

142:

cout "(-1 to stop): " ;

143:

cin >> offset >> value;

144:

if (offset < 0)

145:

break;

146:
147:

if (offset > 9)
{

148:

cout << "***Please use values between 0 and 9.***\ n";

149:

continue;

150:

151:

theArray[offset] = value;

152: }
153: }
154:
155:
156: void AnimalFillFunction(Array<Animal>& theArray)
157: (
158:

Animal * pAnimal;

159:

for (int i = 0; i<theArray.GetSize(); i++)

160: {
161:

pAnimal = new Animal(i*10);

162:

theArray[i] = pAnimal;

163:
164:

delete pAnimal;
}

165: }

618


,
.

1: animal() animal() animal() Enter an offset (0-9) and a value. (-1 to


stop): 0 0
2: Enter an offset (0-9) and a value. (-1 to stop): 1 1
3: Enter an offset (0-9) and a value. (-1 to stop): 2 2
4: Enter an offset (0-9) and a value. (-1 to stop): 3 3
5: Enter an offset (0-9) and a value. (-1 to stop): -1 -1
6:

animal(int)

Destroyed

an

animal...animal(int)

Destroyed

an

animal...animal(int) Destroyed an animal...initArray...


7: [0] 0
8: [1] 1
9: [2] 2
10.
11- animal array...
12

[0] 0

13
14

[1 ]
[2] 20

15
16
17
18
19

Destroyed an animal... Destroyed an


<<< Second run >
animal(int) Destroyed an
animal(int) Destroyed an

20
21

animal(int) Destroyed an

22
23

Enter an offset (0-9) and


Enter an offset (0-9) and

24

Enter an offset (0-9) and

25

animal(int)

26
27

animal(int)

28

Destroyed an animal...

29
30
31

animal(int)

Enter an offset (0-9) and

animal... Destroyed an animal

animal..
animal..
animal..
a value.
a value.
a value.
a value.

(-1 to stop):
(-1 to stop):
(-1 to stop):

0 0
1 1

(-1 to stop):

3 3

2 2

Destroyed an animal...

Destroyed an animal...
initArray...

32

[0] 0

33
34

[1] 1
[2] 2

35
36
37

animal array...

38

[1] 10
[2] 20

39

[0] 0

40
41

Destroyed an animal...

42

Destroyed an animal...

43

Destroyed an animal...

19.6 ,
Animal.
DefaultSize 3.
Animal ( 3348)
, .

19.

619

7481 Array. 114118


Array Animal.
,
Animal
.
.
1
, .
, .
AnimalFillFunction().
Animal ( 161),
Animal ( 162).
( 163) Animal .
6
.
,
. 16
.
( 18-43)
( 114 118),
Array.
Animal ,
74-81.
Animal
( 79 80), 18-20
.
, ,
, .


-.
. ,
- Array (,
),
-: Animal
. -
Array 19.7.

A ugriuni 18.7. - -
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1:

include ciostream.h>

2:
3:
4:

const int DefaultSize = 3;

5:// ,
6:

class Animal

7:
8:

{
public:

620

9:
10:
11:
12:
13:
14;
15:
16:
17;

//
Animal(int);
AnimalO;
'AnimalO;

18:

//
friend ostream& operator (ostreami, const Animal&);

11
int GetWeightO const { return itsWeight; >
void SetWeight(int theWeight) { ItsWeight = theWeight;

19:

20:
21;
22:
23:
24;
25:
26:
27;
28:
29:
30;
31;
32:
33:
34;
35:
36:
37:
38:
39:
40:

private:
Int ItsWeight;
> ;
// Animal
ostreami operator
(ostr@am& theStream, const Animali theAnimal)
{
theStream theAnimal.GetWeightO;
return theStream;
}
Animal::Anlmal(int weight):
itsWeight(weight)
<
//cout "animal(int)

)
AnimalAnimalO:
itsWeight(O)

41; {

cout "animalO
42;
43: }
44:
45; Animal::AnimalO
46: {
47;
//cout "Destroyed an animal...";
48; >
49:
50: template <class T> //
51; class Array
//
52: {
53: public:
54:
//
55:
Array(int itsSize = OefaultSize);
56;
Array(const Array &rhs);
57;
'ArrayO < delete [] pType; itsNumberArrays-; }
58;
59:
//

19.

60:

Array& operator=(const Array&);

61:T& operator^ ](int offSet) { return pType[offSet]; }


62:
63:
64:
65:
66:
67:

const T& operator[](int offSet) const


{ return pType[offSet]; }
//
int GetSize() const { return itsSize; }
static
int
GetNumberArrays()
{
return

68:

// -

itsNumberArrays:

69:friend ostream& operator<< (ostream&, const Array<T>&);


70:
71:

private:

72:

T *pType;

73:

int itsSize;

74:

static int itsNumberArrays;

75:

} ;

76:
77:
78:
79:
80:
81:
82:

template <class T>


int Array<T>::itsNumberArrays = 0;
template <class T>
Array<T>::Array(int size = DefaultSize):
itsSize(size)

83:
84:

{
pType = new T[size];

85:
86:
87:

for (int i = 0; i<size; i++)


pType[i] = (T)0;
itsNumberArrays++;

88:

89:
90:
template <class T>
91: Array<T>& Array<T>::operator=(const Array &rhs)
92:
{
93:
if (this == &rhs)
94:
return this;
95:

delete [] pType;

96:

itsSize = rhs.GetSizeO;

97:
98:
99:

pType = new T[itsSize];


for (int i = 0; i<itsSize; i++)
pType[i] = rhs[i ];

100 :

101 :
102:

template <class T>

103:
104:

Array<T>::Array(const Array &rhs)


{

105:
106:
107:

itsSize = rhs.GetSizeO;
pType = new T[itsSize];
for (int i = 0; KitsSize; i++)

108:

pType[i] = rhs[i ];

109:

itsNumberArrays++;

110:

622

111:
112:
113: template <class T>
114: ostream& operator<< (ostream& output, const Array<T>& theArray)
115: {
116:
for (int i = 0: i<theArray.GetSize(); i++)
117:
output << "[ i << "] " << theArray[i] << endl;
118:

return output;

119: }
120 :

121 :
122:
123: int main()
124: {

125:
126:

cout << Array<int>::GetNumberArrays() << " integer arrays\ n";

127:

cout << Array<Animal>::GetNumberArrays();

128:

cout << " animal arrays\ n\ n;

129:
130:
131:
132:
133:
134:

Array<int> intArray;
Array<Animal> animalArray;
cout << intArray.GetNumberArrays() << " integer arrays\ n";
cout << animalArray.GetNumberArrays();
cout << " animal arrays\ n\ n";

135:
136:
137:

Array<int> plntArray = new Array<int>;

138:
139:

cout << Array<int>::GetNumberArrays() << " integer arrays\ n";


cout << Array<Animal>::GetNumberArrays();

140:

cout << " animal arrays\ n\ n";

141:
142:
143:
144:
145:

delete plntArray;
cout << Array<int>::GetNumberArrays() << " integer arrays\ n";
cout Array<Animal>::GetNumberArrays();

146:
cout << " animal arrays\ n\ n";
147: return 0;
148: }

0 integer arrays
0 animal arrays
1 integer arrays
1 animal arrays
2 integer arrays
1 animal arrays
1 integer arrays
1 animal arrays

19.

623

tf'iWfii Animal.
Array itsNumberArrays (
74), ,
66 GetNumberArrays().
- 77
78. Array ,
, .
, , ,
- :
, , 132 133,
, 126 127.
, -
, -.


.


.


,

.


C++
(Standard Template Library STL).
STL
. STL ,
. , , ,
, .
STL ,

. STL ,
. , STL
.
STL .

, .
C++ -,
, C++
.
(STL) : .

624

, .
,
. C++,
STL . -
STL std.



. C++
: , .


. ,
. STL vector, ,
C++.
, ,
. - vector
<vector> std (
. 17). .
, 10 .
10 , .
, ,
. vector:
template <class , class
{
//
> ;

= ailocator<T>> class vector

(class ) .
(class ) ,
,
.
, .
new()
delete(), ..
.
.
,
.

:
vector<int> vlnts;

//

vector<float> vFloats;

//

19.

625

,
. ,
50 . ,
, 50
. vector ,
. 50
:
vector<Student> MathClass(50);


50 .
Student: ;Student().
- size().
- vStudent. size() 50.
-, capacityQ, ,
, . .
, , ..
. , ,
- empty(), , ,
.
, .. (
) Harry
Student

MathClass, ([]):
MathClass[5] = Harry;

. Harry
MathClass
Student. , Harry,
, :
MathClass[5].GetAge();

, ,
,
. ,
, 50. , 51 - , ,
. , ( MathClass)
51- ( Sally),
, .
.
- push_back():
MathClass.push_back(Sally);

- Sally Student
MathClass 51 ,
Sally MathClass[50].
push_back() , Student
-.
Sally.
MathClass.

626

STL ,
.
- max_size(),
, .
19.8 . ,

string. string
, .

13.8. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1:

include <iostream>

2:

include <string>

3:

#include <vector>

4:

using namespace std;

5:
6: class Student
7: {
8:

public:

9:
10:

StudentO;
Student(const string& name, const int age);

11:

Student(const Student& rhs);

12:

"StudentO;

13:
14:

void SetName(const string& name);

15;

string GetName() const;

16;

void SetAge(const int age);

17:

int

GetAgeO

const;

18:
19;

Student& operator=(const Student& rhs);

20:
21: private:
22:

string itsName;

23:

int itsAge;

24: } ;
25:
26: Student::Student()
27: : itsNameC'New Student"), itsAge(16)
28: { }
29:
30: Student::Student(const string& name, const int age)
31: : itsName(name), itsAge(age)
32: { }
33:
34: Student::Student(const Student& rhs)
35: : itsName(rhs.GetName()), itsAge(rhs.GetAge())
36: { }
37:
38; Student:: "StudentO
39: { }
40:

19.

627

41:

void Student::SetName(const string& name)

42:
43:

itsName = name;

44:
45:
46:

tring Student::GetName() const

47:
48:

return itsName;

49:
50:
51:

old Student::SetAge(const int age)

52:
53:

itsAgs = age;

54:
55:
56:

nt Student::GtAge() const

57:
58:
59:
60:
61:

return itsAge;

tudant& Student::operator=(eonst Studenti rhs)

62:
63:
64:

itsName
itsAge

65:
66:

=
=

rhs.GetName();
rhs.QitAgeO;

return this;

67:
68:

streams. operator(ostream& os, const Students rhs)

69:
70:

os rhs.GetName() " is rhs,GetAge() years old";

71:

return os;

72:
73:
74:

template<class T>

75:

void ShowVector(const vector<T>& v); //

76:
77:

typedef vector<Student>

SchoolClass;

78:
79:

int main()

80:

81:

Student Harry;

82:

Student Sally"Sally", 15);

83:

Student Bill("BiH", 17);

84:

Student Peter("Peter", 16);

85:

86:

SchoolClass EmptyClass;

87:

cout << "EmptyClass:\ n";


ShowVector(EmptvClass);

88 :
89:
90:

SchoolClass GrowingClass(3);

91:

cout << ''GrowingClass(3) :\ n";

92:

ShowVector(GrowingClass);

93:
94:

GrowingClass[0] = Harry;

95:

GrowingClass[1] = Sally;

96:

GrowingClass[2] = Bill;

97:

cout << "GrowingClass(3) after assigning students:\ n";

98:

ShowVector(GrowingClass);

99:
100:

GrowingClass.push_back(Peter);

101:

cout << "GrowingClass() after added 4th student:\ n";

102:

ShowVector(GrowingClass);

103:
104:

GrowingClass[0].SetName("Harry");

105:

GrowingClass[0].SetAge(18);

106:

cout << "GrowingClass() after Set\n:";

107:

ShowVector(GrowingClass);

108:
109:

return 0;

110: }
111:
112 : / /
113: //
114: //
115: templatecclass T>
116: void ShowVector(const vector<T>& v)
117: {
118:

cout "max_size() = " v,max_size();

119:

cout "\ tsize() = " << v,size();

120;

cout << "\ tcapacityO = " v,capacity();

121:

cout << "\ t" (v.emptyO? "empty": "not empty");

122:

cout << "\ n";

123:
124:

for (int i s 0; i < v,size(); ++i)

125:
126:
127:

cout v[i] "\ n";


cout endl;

128: }
129

EmptyClass:
max_size() = 214748364 size() = 0

capacityO = 0 empty

GrowingClass(3):
max_size() = 214748364

size()

New Student is 16 years

old

New Student is 16 years

old

New Student is 16 years

old

19.

capacityO = 3 not empty

629

GrowingClass(3) after assigning students:


max_size() = 214748364 size() = 3 capacityO = 3 not empty
New Student is 16 years old
Sally is 15 years old
Bill is 17 years old
GrowingClassO after added 4th student:
max_size() = 214748364 size() = 4 capacityO = 6 not empty
New Student is 16 years old
Sally is 15 years old
Bill is 17 years old
Peter is 16 years old
GrowingClass() after Set:
max_size() = 214748364 size() = 4 capacityO = 6 not empty
Harry is 18 years old
Sally is 15 years old
Bill is 17 years old
Peter is 16 years old

Student 624,
- 2666.
vector.
, -
. , - itsName
C++ string. ,
C++ , ( char*).
ShowVector() 7475
115-128. - ,
: max_size(), size(), capacityO emptyO-
, Student,
, Visual C++ 214 748 364.
. ,
1 073 741 823 . ,
.
124 125 ,
, (),
6872.
8184 Student. 86

EmptyClass. ,

ShowVector(EmptyClass), , .
90
Student. , , .
9496 ([]) GrowingClass
Student.
100 (Peter).
. ,
. ,

630

, Student.
,
.
, Student.
,
. ,
.
.
( )
. ,
,
, .
104 105 ([]),
- GrowingClass.


, -

-
.

- -. front()
, back() .
at() ([]). ,
,
. ,
out_of_range. ( .)
insert() ()
. Pop_back() . ,
remove() .

,
.
- STL list <list>
std. list ,
,
.
list -, .
, , ,
. - list
, .
. ,
, .
19.9.

19.

631

13.9.
1: include <iostream>
2: include <1ist>
3:

using namespace std;

4:
5: typedef list<int> IntegerList;

6:
7: int main()

8: {
9:

IntegerList intlist;

10 :
11:

for (int i = 1; i <= 10; ++i)

12:

intList.push_back(i * 2);

13:
14:

for (IntegerList::const_iterator ci = intList.begin();

15:

ci != intList.end(); ++ci)

16:

cout *ci "

17:
18:

return 0;

19: }

T* 2 4 6 8 10 12 14 16 18 20
V

5' I'"- ' 9 int Li st . 11 12 push_baek()


10 .
14-16 ,
. ,
. , ,
:
intlist: iterator

- begin() .
(++) .
- end(), , ,
. end()
.
( )
, 16.
list,
. , ,
push_front() pop_front(), ,
push_back() pop_back().
, .

632



- vector
. , , deque
.
- list,
.
,
.
,
.
,
.


. , ,
. stack
<stack> std.
,
, ..
.
, vector deque.
,
back(), push_back() pop_back().
, stack.
stack STL
. ,
.
.
: , ,
, .
- , , ,
. - ( )
, , ,
, , .
, ,
, (push) (pop) .
stack .

stack STL ,
,
,
.

19.

633


.
, .
. .
. (
), () (
), .. , .
, .
, . ,
- (, ),
, ,
, . .
stack, queue .
, frontQ, back(), push_back() pop_front().



,

. ++
: , , .

.
. ,
:
,
.
, .
19.10 ,
19.8, .

19.1D. -
include <iostream>

2
3

ftinclude <string>

using namespace std;

include <map>

class Student

public

9:

Student();

10 :

Student(const

11:

Student(const Student& rhs);

634

string&

name,

const

int

age);

12:

"StudentO;

13:
14:

void SetName(const string& name);

15:

string GetNameO const;

16':
17:

void SetAge(const int age);


int
GetAgeO

18:
19:

Student& operator=(const Student& rhs);

const;

20:
21: private:
22:

string itsName;

23:

int itsAge;

24: } ;
25:
26: Student::Student()
27: : itsName(New Student"), itsAge(16)
28: { }
29:
30: Student::Student(const string& name, const int
31: : itsName(name), itsAge(age)
32: { }
33:
34: Student::Student(const Student& rhs)
35: : itsName(rhs.GetName()), itsAge(rhs.GetAge())
36: { }
37:
38: Student::~Student()
39: < }
40:
41: void Student::SetName(const string& name)
42: {
43:

itsName = name;

44: }
45:
46: string Student::GetName() const
47: {
48:

return itsName;

49: }
50:
51: void Student::SetAge(const int age)
52: {
53:

itsAge = age;

54: }
55:
56: int Student::GetAge() const
57: {
58:

return itsAge;

59: }
60:
61: Student& Student::operator=(const Student& rhs)
62: {

19.

63:

itsName = rhs,GetName();

64:

itsAge = rhs.GetAge();

65:

return *this;

66: }
67:
68: ostream& operator<<(ostream& os, const Student& rhs)
69: <
70:
71:
72: }

os << rhs.GetName() << " is " << rhs.GetAge() << " years old";
return os;

73:
74: template<class T, class A>
75: void ShowMap(const map<T, A>& v); //
76:
77: typedef map<string, Student> SchoolClass;
78:
79: int main()
80: {
81:

Student HarryC'Harry", 18);

82:
83:
84:
85:

Student Sally("Sally", 15);


Student Bill("Bill", 17);
Student PeterC'Peter", 16);

86:
87:

SchoolClassMathClass;
MathClass[Harry.GetNane()] = Harry;

88:

MathClass[Sally.GetName()] = Sally;

89:
90:

MathClass[Bill.GetName()] = Bill;
MathClass[Peter,GetName()] = Peter;

91:
92:

cout "MathClass:\ n";

93:
94:

ShowMap(MathClass);

95:
96:
97:

cout "We know that " << MathClass["Bill" ], GatName()


<< " is " MathClass["Bill"].GetAge() << "years old\ n";

98:

return 0;

99: }

100:

101: //
102: //
103: //
104: template<class T, class A>
105: void ShowMap(const map<T, A>& v)
106; {
107:

for (mapd, A>::const_iterator ci = v.begin();

108:
109:
110:
111:

ci ! = v.end(); ++ci)
cout << ci->first << " << ci->second << "\ n";
cout << endl;

112:}

636

MathClass:
Bill: Bill is 17 years old
Harry

Harry is 18 years old

Peter

Peter is 16 years old

Sally

Sally is 15 years old

We know that Bill is 17 years old

3 <>,
- .
ShowMap. 77
SchoolClass ,
(, ). .
SchoolClass
,
string.
, ..
. ,
Student. STL (
struct), , : first second.
.
main () ShowMap,
. ci->first
( 109) ( ), ci->second
Student.
81-84 Student. MathClass
SchoolClass ( 86), 87-90
MathClass:
map_object[key_value] = object_value;


push_back() insertO (
, ).
Student
, . 95 96
, ( Bill),

MathClass["BiH"].


- ,
. , ,
.
- .
, -, .
, - ,
.

19.

637


.

.

, . ,
, ,

. 60
,
, .
<1> !.
, ,
. ,
().
. 19.11.

13.11. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: ((include <iostream>
2: using namespace std;
3:
4: template<class T>
5: class Print {
6: public:
7:

void operator( )(const T8, t)

8: <
9:
10:

cout << t <<


}

11: } ;
12:

13: int main()


14: {
15:

Print<int> DoPrint;

16:

for (int i = 0; i < 5; ++i)

17:
18:

DoPrint(i);
return 0:

19: }

0 12 3 4

411 Print.
710
. 15 DoPrint
Print. , ,
DoPrint , 17.

638

,
, ,
, ^_!1 () 11(), , ..
19.12 ^_,
.

18.12. _ ) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: include <iostream>
2: include <vector>
3: include <algorithm>
4: using namespace std;
5:
6: template<class T>
7: class Print

8: {
9: public:
10:

void operator()(const T& t)

11: {
12:
13:

cout t << "


}

14: } ;
15:
16: int main()
17: {
18:

Print<int> DoPrint;

19:

vector<int> vlnt(5);

20:
21:
22:

for (int i = 0; i < 5; ++i)


vlnt[i] = i * 3;

23:
24:

cout << "for_each()\ n";

25:

for_each(vInt.begin(), vlnt.end(), DoPrint);

26:
27:

cout << "\ n";

28:

return 0;

29: }

for_each()
0 3 6 9 12

, C++
<algoritlnm>,
. . 25
for_each(), vint.
DoPrint
DoPrint.operator(), .

19.

639



. ,
.
19.13.

18.13. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
1: include <iostream>
2: include <vector>
3: include <algorithm>
4: using namespace std;
5:
6: template<class T>
7: class Print

8: {
9: public:
10:

void operator()(const T& t)

11: {
12:
13:

cout t "
}

14: } ;
15:
16: int mainO
17: {
18:

Print<int> DoPrint:

19:

vector<int> vlnt(10);

20:
21:

fill(vlnt.begin(), vlnt.begin() + 5, 1);

22:

fill(vlnt.begin() + 5, vlnt.end(), 2);

23:
24:

for_each(vInt. begin(), vlnt.endO, DoPrint);

25:

cout << "\ n\ n";

26:
27:

return 0;

28: }

l'f5"'*'' ' 1 1 1 1 1 2 2 2 2 2

1 ,

21 22,
fill().
. 21
1 vint.
vint 2 ( 22).

640


,
++, , ., ,
,
. ,
, .
.
,
: , ..
-:
, .
.
.

, .


?

.


?
( ) ,
.
. ,
, .

, ?
,
, , .

?
, ,
.

,
?
--.
, <1^> 1<11:>,
111>.

?
.

.
.

19.

641

,
?
, .


, ,
. ,
.
,
.


1. ?
2. ?
3.
, ?
4. ?
5. - ,
?
6. ?
7. ?

1. List:
class List

<
private:
public:
List():head(O),tail(O),theCount(O) { }
virtual ~List();
void insert( int value );
void append( int value );
int is_present( int value ) const;
int is_empty() const { return head == 0; }
int count() const { return theCount; }
private:
class ListCell

{
public:
ListCell(int value, ListCell *cell =
):val(value),next(cell){ }

642

int val;
ListCell *next;

>;
ListCell *head;
ListCell *tail;
int theCount;

2.

};
( ) List.

3.

4.
5.

; Strings, Cat int.


: ? (,
List, a Cat ,
.)
List<Cat> Cat_List;
Cat Felix;
CatList.append( Felix );
cout << "Felix is " <<
( Cat_List.is_present( Felix ) ) ? "" : "not " << "present\ n";

6.

( ): ,
int?

7.

operator== List.

8.

operator== List.

9.

operator== , 5?

10.

,
, .

Cat

11.

SchoolClass, 19.8, .
push_back().
.
12. 10 ,
.

19.

643



, , .
,
, .
.
:

, ,
, . ,
,
,
. ,
,
, .

, .
, ,
. ,
, ,
.
.
.

644

, .. ,
. ,
.
,
, . ,
,
.
, . ++
,
.
, ,
, ,
, .
, ,
, .. ,
, , ,
, , .
- , ,
.
,
. ,
:
, , .
,
, , ,
,
, - , ,
(
).



,
.

.

. , ,
. ,

, , .
:

, .

20.

645

, .. , ,
.
, - ,
, ,
.
++
, .


, ,
, .
- , ,
,

.
, .

,
,
, .
-- '

,
,
.
, , -
,
, .
,
.

, ,
, - , , .
, ,
,
,
.

++ , ,
, , .
,
, , .
.

(,
) .

646

, -

,
.


. ,
,
, .


try ,
, :
try

{
SomeDangerousFunction{);

}
, try, catch, :
try

{
SomeDangerousFunction();

>
catch{OutOfMemory)

{
11

>
catch(FileNotFound)

{
//

}
.
1.

, ,
, try.

2.

catch , ,
.
20.1 try catch.

,
.
try ,
, .
catch , try
.
catch,
t .

20.

647


.
ANSI C++.
. ,
,
.
, .

20.1.
1:

include <iostream.h>

2:
3:
4:

const int DefaultSize = 10;

5:

class Array

6: {
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:

public:
//
Array(int itsSize = DefaultSize);
Array(const Array &rhs);
"ArrayO { delete [] pType; }
//
Array& operator=(const Array&);
int& operator[](int offSet);
const int& operator!](int offSet) const;
//
int GetitsSize() const { return itsSize; }

20:
21:

// -

22:

friend ostream& operator<< (ostream&, const Array&);

23:
24:
25:
26:

class xBoundary { } ; //
private:
int *pType;

27:
28: } ;

int itsSize;

29:
30:
31:
32:

Array::Array(int size):
itsSize(size)

33:

34:
35:

36:
37:

pType = new int[size];


for (int i = 0; i<size; i++)

pTypet i] = 0;
}

38:
39:
40:
41:
42:

648

Arrayi Array::operator=(const Array &rhs)


{
if (this == &rhs)

43:

return *this;

44:
45:

delete [] pType;
itsSize = rhs.GetitsSizeO;

46:

pType = new int[itsSize];

47:
48:
49:
50:
51:
52:

for (int i = 0; KitsSize; i++)


pType[i] = rhs[i];
return *this;
}
Array::Array(const Array &rhs)

53:
54:
55:
56:
57:

58:

itsSize = rhs.GetitsSizeO;
pType = new int[itsSize];
for (int i = 0; KitsSize; i++)
pType[i] = rhs[i];

59:
60:
61:
62: {
63:
64:
65:
66:
67:

int& Array::operator[](int offSet)


int size = GetitsSize();
if (offSet >= 0 && offSet < GetitsSize())
return pType[offSet];
throw xBoundaryO;
return pType[0]; //

68: }
69:
70:
71:

const int& Array::operator[](int offSet) const

72:

73:
74:
75:
7'6:
77:
78:

Int mysize = GetitsSizeO:


if (offSet >= 0 && offSet < GetitsSizeO)
return pType[offSet];

79:
80:

ostreami operator (ostream& output, const Arrayi theArray)

throw xBoundaryO;
return pType[0]; //

81: {

82 ;
83;
84:
85;

for (int i = 0 ; KtheArray, GetitsSizeO: i++)


output "[" i "] " theArray[i] endl;
return output;
}

86 ;
87; int main()

88: {
89:

Array intArray(20);

90:
91:
92:

try
{

93:
94:

for (int j = 0; j< 100; j++)

(
intAr ray[j] = j;

20.

95:
96:
97:

cout "intArray[" j << "] okay..." << endl;


}

98:
99:
100:

catch (Array::xBoundary)
{
cout << "Unable to process your input!\ n";

101: }
102:
103:
104:

. -

cout << "Done.\ n";


return 0;
}

intArray[0] okay...
intArray[1]

okay...

intArray[2]

okay...

intArray[3]

okay...

intArray[4]

okay...

intArray[5]

okay...

intArray[6]

okay...

intArray[7]

okay...

intArray[8]

okay...

intArray[9]

okay...

intArray[10]

okay...

intArray[11]

okay...

intArray[12]

okay...

intArray[13]

okay...

lntArray[14]

okay...

intArray[15]

okay...

intArray[16]

okay..,

intArray[17] okay...
IntA'rray[ 18] okay. . .
intArray[19] okay...
Unable to process your input!
Done.

20.1 Array,
, 19.
24 xBoundary

Array.

.
. .
,
, ,
, - (=),
, .
, Array
. 15, Array
xBoundary, xBoundary
Array.

650

6168 7178 ([])


, ,
, xBoundary
. ,
xBoundary .
, Microsoft ,
return,
(
),
66 67.
, Microsoft!
90 try
, 97. ,
89, 101 .
98 catch xBoundary.
87104 try,
. j ( 92)
20, , 20.
64,
operator[] xBoundary ( 66).
catch 98,
catch ,
. catch 100.


,
try, ;
.
.:
try
{
FunctionQ;
>


,
, .
. catch .
:
try ' ................ .

catch,

.................

::

//

:-

20.

651

try catch
, try,
, .
, . ,
, , , ,
,
.
try ,
. ,
, .,
.


.
, .
, , .
. main()
Animal : :GetFavoriteFood( ), GetFavoriteFood( )
Animal
:: LookupPreferences(
), , ,
fstream: :operator(), .
.
.
,
.
try catch.
catch,
.
catch, .
( main( ))
, , .

. .
. ,
catch, .
, 20.1
101 tr catch, xBoundary.
,
catch, , .

catch

.
catch, ,
switch. default
c a t c h ( . , , ) , .
20.2.

652

20.2.
1: #include <iostream.h>

2:
3: const int DefaultSize = 10;
4:
5; class Array

6: {
7: public:
8:
9:

//
Array(int itsSize = DefaultSize);

10:

Array(const Array &rhs);

11:

"ArrayO { delete [] pType;}

12:

13:

//

14:

Array& operator=(const Array&);

15:

int& operator[](int offSet);

16:

const int& operator[](int offSet) const;

17:
18:
19:

//
int GetitsSize() const { return itsSize; }

20:
21:
22:

// -
friend ostream& operator (ostream&, const Array&);

23:
24: //
25:

class xBoundary { } ;

26:
27:

class xTooBig { } ;
class xTooSmall{ } ;

28:

class xZero { } ;

29:

class xNegative { } ;

30: private:
31:

int pType;

32:

int itsSize;

33: } ;
34:
35:

int& Array::operator[](int offSet)

36:

37:

int size = GetitsSize();

38:

if (offSet >= 0 J,& offSet < GetitsSize())

39:

return pType[offSet];

40:

throw xBoundaryO;

41:
42:

return pType[0]; //
}

43:
44:
45:
46:
47:
48:

const int& Array::operator[](int offSet) const


{
int mysize = GetitsSize();
if (offSet >= 0 && offSet < GetitsSizeO)

20.

653

49:

return pType[offSet];

50:

throw xBoundary();

51:
52:

return pType[0]; //

>

53:
54:
55:
56:
57:

Array::Array(int size):
itsSize(size)

58:

59:

if (size == 0)

60:

throw xZero();

61 :

if (size < 10)

62:

throw xTooSmall();

63:

if (size > 30000)

64:

throw xTooBigO;

65:

if (size < 1)

66:

throw xNegative():

67:

68:

pType = new int[size];


for (int i = 0; i<size: i++)

69:
70:
71 :

pType[i] = 0;

72:
73:
74:
75:

int main()

76:

77:
78:

try

79:

80:

Array intArray(O);

81 :

for (int j = 0; j< 100; j++)

82:
83:
84:

{
intArray[j] = j;
cout << "intArray[" j << "] okay...\ n";

>

85:

86:

87:

catch (Array:.xBoundary)

88 :

89:

cout << "Unable to process your input !\ n";

90:

91:

catch (Array::xTooBig)

92:

93:
94:

95:

catch (Array::xTooSmall)

96:

97:

cout << "This array is too big...\ n";

cout << "This array is too small...\ n";

98:

99:

catch (Array::xZero)

100: {
101:

cout << "You asked for an array";

102:

cout << " of zero objects!\ n";

103:

104:

catch (...)

105:

106:

cout << "Something went wrong!\ n";

107:

108:

cout << "Done.\ n";

109:
110 :

return 0;
}

.. , - You asked for an array of zero objects!


Done

2629 : xTooBig, xTooSmall, xZero


5671 ,
. , ,
.
try catch
, , .
catch(. ..) 104.
.
-5. ,
xNegative, , :
size < 10 size < 1. ,
61 62 65 66 .
xNegative.


, , .
, xSize xZero,
xTooSmall, xTooBig xNegative.
xSize, , xSize.
20.3.

20.3.
1:

include <iostream.h>

2:
3:
4:

const int DefaultSize = 10;

5:

class Array

6:

7:
8:

public:
//

9:
10:

Array(int itsSize = DefaultSize);


Array(const Array &rhs);

20.

655

"ArrayO { delete [] pType;}

11 :
12:
13:

//

14:

Array& operator=(const Array&);


int& operator^ ](int offSet):

15:
16:
17:

const int& operator^](int offSet) const;

18:

//

19:

int GetitsSizeO const { return itsSize; }

20:
21:
22:
23:
24:
25:

// -
friend ostrean& operator<< (ostream&, const Array&);
//
class xBoundary < } ;

26:
27:

class xSize { } ;

28:
29:

class xTooSmall : public xSize { } ;

30:
31:
32:
33:

class xTooBig : public xSize { } ;


class xZero : public xTooSmall { } ;
class xNegative : public xSize { } ;
private:
int pType;
int itsSize;

34:
35:
36:
37:

Array::Array(int size):

38:

itsSize(size)

39:

<

40:
41:

if (size == 0)
throw xZero();

42:
43:
44:

if (size
throw
if (size
throw
if (size

45:
46:
47:
48:
49:

throw xTooSmall();
pType = new int[size];
for (int i = 0; i<size; i++)

50:
51:
52:

pType[i] = 0;

53:
54:
55:
56:
57:
58:
59:
60:
61:

> 30000)
xTooBig();
<1)
xNegative();
< 10)

int& Array::operator[](int offSet)

<
int size = GetitsSizeO;
if (offSet >= 0 && offSet < GetitsSizeO)
return pType[offSet];
throw xBoundary();
return pType[0]; //

62:
63:
64:
65:
66:
67:
68:
69:

const int& Array::operator[](int offSet) const


{
int mysize = GetitsSize();
if (offSet >= 0 && offSet < GetitsSizeO)
return pType[offSet];
throw xBoundaryO;

70:
71:
72:
73:

return [0]; //
}

74: int main()


75: <
76:
77:
78:
79:
80:
81: {
82:
83:

try
{
Array intArray(O);
for (int j = 0; j< 100; j++)
intArray[j] = ];
cout << "intArray[" j << "] okay...\ n";

84:

>

85:
86:

}
catch (Array::xBoundary)

87:
88:

89:
90:

}
catch (Array::xTooBig)

91:
92:

93:
94:
95:

96:
97:
98:
99:

cout << "Unable to process your input!\ n";

cout "This array is too big...\ n";

catch (Array::xTooSmall)
{
cout "This array is too small...\ n";
}
catch (Array::xZero)

100: {
101:

cout << "You asked for an array";

102:
103:
104:

cout << " of zero objects!\ n";


}

105:
106:
107:
108:
109:
110:
111:

catch (...)
{
cout "Something went wrong!\ n";
}
cout << "Done.\ n";
return 0;

112: }

20.

657

This array is too small


Done.

2730,
. xTooBig, xTooSmall xNegative
xSize, xZero xTooSmall.
Array , ? ,
!
catch, , , xZero,
xTooSmall. xZero,
xTooSmall,
xTooSmall. ,
, xZero .

, ,
.
xZero xTooSmall.



,
, , .
, .
,
, 20.4.

20.4. ______________________________
1:

#include <iostream.h>

2:
3:

const int DefaultSize = 10;

4:
5:

class Array

6;

7;

public:

8:

//

9:

Array(int itsSize = DefaultSize);

10:

Array(const Array &rhs);

11:

"ArrayO { delete [] pType; }

12:
13:

//

14:

Array& operator=(const Array&);

15:

int& operatorf](int offSet);

16:

const int& operator[ ](int offSet) const;

17:
18:

658

//

19:

int GetitsSizeO const { return itsSize; }

20:
21:

// -

22:

friend ostream& operator (ostream&, const Array&);

23:
24:

//

25:

class xBoundary { } ;

26:

class xSize

27:

28:

public:

29:

xSize(int size):itsSize(size) { }

30:

xSize(){ }

31:

int GetSize() { return itsSize; }

32:

private:

33:

int itsSize;

34:

} ;

35:
36:

class xTooBig : public xSize

37:

38:

public:

39:

xTooBig(int size):xSize(size){ }

40:
41:

} ;

42:

class xTooSmall : public xSize

43:

44:

public:

45:

xTooSmall(int size):xSize(size){ }

46:
47:

} ;

48:

class xZero : public xTooSmall

49:

50:
51:

public:
xZero(int size):xTooSmall(size){ }

52:

} ;

53:
54:

class xNegative : public xSize

55:

56:

public:

57:

xNegative(int size):xSize(size){ }

58:

} ;

59:
60: private:
61:

int *pType;

62:
63: } ;
64:

int itsSize;

65:
66: Array::Array(int size):
67:

itsSize(size)

68: {

20.

69:

if (size == 0)

70:

throw xZero(size);

71:

if (size > 30000)

72:

throw xTooBig(size);

73:

if (size <1)

74:

throw xNegative(size);

75:

if (size < 10)

76:
77:

throw xTooSnall(size);

78:

pType = new int[size];

79:

for (int i = 0; i<size; i++)

80:

pType[i] = 0;

81: >
82:
83:
84:

inti Array::operator[] (int offSet)

'

85: {
86:

int size = GetitsSizeO;

87:

if (offSet >= 0 && offSet < GetitsSizeO)

88:

return pType[offSet];

89:
90:

throw xBoundaryO;
return pType[0]:

91: }
92:
93: const int& Array::operator[] (int offSet) const
94:

95:
96:

int size = GetitsSizeO;


if (offSet >= 0 && offSet < GetitsSizeO)

97:

return pType[offSet];

98:

throw xBoundaryO;

99:
100 : }

return pType[0];

101:
102:

int main()

103:

104:
105:

try

106: {
107:

Array intArray(9);

108:

for (int j = 0; j< 100; j++)

109:

110:

intArray[j] = j;

111:

cout "intArray[" j << "] okay..." endl;

112 : }
113:
114:

>
catch (Array::xBoundary)

115:

116:
117:
118:

660

cout << "Unable to process your input!\ n";


}
catch (Array::xZero theException)

119:
120:

{
cout "You asked for an Array of zero objectai " endl;

121:

cout "Received " theException,GetSizeO endl;

122: }
123:

catch (Array::xTooBig theExceptlon)

124:

125:
126:

cout << "This Array is too big,,, << endl;


cout "Received " theException,GetSize() endl;

127:

128:

catch (Array;:xTooSmall theException)

129:

130:

cout << "This Array is too small... " << endl;

131:

cout << "Received " << theException.GetSize() << endl;

132:

133 :
134:

catch (...)
{

135:
136:
137:
138:

cout << "Something went wrong, but I've no idea what!\ n";
}
cout << "Done.\ n";
return 0;

139: >

This array is too small,.,


Received 9
Done.

xSize ,
- itsSize ( 33) - GetSizeO
( 31). , ,
-, 29.
,
. (
).
catch 114-136 ,
(thoException),
catch , - itsSize.

:
, , - ,
,
. ,
OutOfMemory,
- .

^,
. ,
.
,

20,

661

. 20.5
,
- .
, .

20.5.
___________________________________________________________
1:

#! <1:.>

2
3

const int DefaultSize = 10;

4
5

class Array

6
7

public:

//

9;

Array(int itsSize = DefaultSize);

10

Array(const Array &rhs);

11

"ArrayO { delete [] pType; }

12
13

//

14

Array& operator=(const Array&);

15

int& operator[](int offSet);

16

const int& operator[](int offSet) const;

17
18

//

19

int GetitsSize() const { return itsSize; }

20
21
22

// -
friend ostreamS operator<<
(ostream&, const Array8.);

23
24
25

//

26

class xBoundary { } ;

27

class xSize

28
29

public:
xSize(int size):itsSize(size) { }

30
31

~xSize(){ }

32

virtual int GetSizeO { return itsSize; }

33

virtual void PrintError()

34
35

cout << "Size error. Received

36

cout << itsSize << endl;

37
38

protected:
int itsSize;

39
40

> ;

41
42

662

class xTooBig : public xSize

43:

44:

public:

45:

xTooBig(int size):xSize(size){ }

46:

virtual void PrintErrorO

47:

48:

cout "Too big. Received:

49:

cout xSize::itsSize << endl;

50:

51:
52:

} ;

53:

class xTooSmall : public xSize

54:

55:

public:

56:

xTooSmall(int size) :xSize(size){ }

57:

virtual void PrintErrorO

58:

59:

cout << "Too small. Received:

60:

cout << xSize::itsSize endl;

61: >
62: } ;
63:
64:
65:

class xZero : public xTooSmall


{

66:

public:

67:
68:

xZero(int size):xTooSmall(size){ }
virtual void PrintErrorO

69:

70:

cout << "Zero!. Received: " ;

71:

cout << xSize::itsSize << endl;

72:
73:

}
} ;

74:
75:
77:

class xNegative : public xSize76:


public:

78:
79:

xNegative(int size):xSize(size){ }
virtual void PrintErrorO

80: {
81:

cout << "Negative! Received: ";

82:
83:
84:

cout xSize:'.itsSize endl;


}
} ;

85:
86:

private:

87:

int *pType;

88:

int itsSize;

89: } ;
90:
91: Array::Array(int size):
92: itsSize(size)
93: {

20.

94:

if (size - 0)
throw xZero(size);

95:

if (size > 30000)

96:

throw xTooBig(size);

97:
98:

if (size <1)
throw xNegative(size);

99:

if (size < 10)

100:
101 :

throw xTooSmall(size);

102:

103:

pType = new int[size];

104:

for (int i = 0; i<size; i++)


pTypeti] = 0;

105:
106:
107:

>

108:

int& Array::operator[] (int offSet)

109:

110 :

int size = GetitsSize();

111:
112:

if (offSet >= 0 && offSet < GetitsSize())


return pType[offSet];
throw xBoundary();
return pType[0];

113:
114:
115:

>

116:
117:

const int& Array::operator[] (int offSet) const

118:

119:

int size = GetitsSizeO;

120:

if (offSet >= 0 && offSet < GetitsSizeO)

121 :

return pType[offSet];
throw xBoundaryO;

122:

return pType[0];

123:
124:

125:
126:
127:

int main()

128:
129:

try

130:

131:

Array intArray(9);

132:

for (int j = 0; j< 100; J++)

133:

134:

intArray[j] - j;

135:

cout "intArray[" j "] okay...\ n";

136:
137:
138:

I
oatoh (Array::xBoundary)

139:

140:
141:

142:

catch (Array::xSize& theException)

143:

cout "Unable to process your input I\ n";

144:
145:

theExoeptlon.PrintError();

146:

catch (.,,)

147:

148:

cout "Something went wrong!\ n";

149:

150:

cout "Done.\ n";

151:
152: }

return 0;

Too small! Received: 9


' Done.

20.5 PrintError()
* xSize,
. .
142 , .
PrintError()
PrintError().
, , , .
J


, ,
. ,
,
, . 20.6.

20..
1:

include <iostream.h>

2:

3:
4:

const int DefaultSize = 10;


class xBoundary { } ;

5:
6:
7:

template <class T>


class Array

8:

9:

public:

10:

//

11:

Array(int itsSize = DefaultSize);

12:

Array(const Array &rhs);

13:
14:
15:
16:
17:

'ArrayO { delete [] pType;}

18:
19:

//
Array& operator=(const Array<T>&);
T& operator[](int offset);
const T& operator[](int offSet) const;

20.

665

20:
21:

//
int GetitsSizeO const { return itsSize; }

22:
23:
// -
24:friend ostream& operator (ostream&, const Array<T>&);
25:
26:

//

27:
28:

class xSize { } ;

29:
30:

private:

31:

int pType;

32:

int itsSize;

33:
34:

} ;

35:

template Cclass T>

36:

Array<T>::Array(int size):

37:

itsSize(size)

38:
39:
40:

{
if (size <10 || size > 30000)
throw xSize();

41:
42:

pType = new T[size];


for (int i = 0; i<size; i++)

43:

pType[i] = 0;

44:

45:
46:
template cclass T>
47: Array<T>& Array<T>::operator=(const Array<T> &rhs)
48:
49:
50:

{
if (this == &rhs)
return this:

51:
52:

delete [] pType;
itsSize = rhs.GetitsSize();

53:
54:

pType = new T[itsSize];


for (int i = 0; i<itsSize; i++)

55:

pType[i] = rhs[i];

56:
57:
58:

}
template <class T>
Array<T>::Array(const Array<T> &rhs)

59:
60:

{
itsSize = rhs.GetitsSizeO;

61:

pType = new T[itsSize];

62:

for (int i = 0; KitsSize; i++)

63:

pType[i] = rhs[i];

64:

65:
66:
67:

template <class T>


T& Array<T>::operator[](int offSet)

68:

69:

int size = GetitsSizeO;

70:

if (offSet >= 0 && offSet < GetitsSizeO)

666

71:
72:

return pType[offSet];
throw xBoundaryO;

73:
74: }

return pType[0];

75:
76: template <class T>
77: const T& Array<T>::operator[](int offset) const
78: {
79:

int mysize = GetitsSize();

80:

if (offSet >= 0 && offSet < GetitsSize())

81:
82:

return pType[offSet];
throw xBoundaryO;

83: >
84:
85:

template <class J>

86:
87:

ostream& operator (ostream& output, const Array<T>& theArray)


{

88:
89:
90:
91: }

for (int i = 0; KtheArray. GetitsSize(); i++)


output << "[" << i "] " << theArray[i] << endl;
return output;

92:
93:
94:

int main()

95: {
96:
97:

try

98:

99:

Array<int> intArray(9);

100:

for (int j = 0; j< 100; j++)

101 : {
102:

intArray[j] = j;

103:
104:

cout << "intArray[" << j << "] okay..." endl;


}

105:
106:

}
catch (xBoundary)

107:

108:
109:

110:

catch (Array<int>::xSize)

cout "Unable to process your input!\ n";

111: {
112:

cout << "Bad Size!\ n";

113:
114:

115:

cout << "Done.\ n";

116:
117:

return 0;
}

You asked for an array of zero objects!

Mud,i mM* pQne

20.

667

, xBoundary, 4; , xSize, 28.


xBoundary ,
, . XSize
Array.
catch. 106 catch (xBoundary),
110 catch (Array<int>::xSize).
.


C++
, ,
,
. ,
, ,
, .
,
,
. .
GUI (
). , ,
- , , , ,
. , ,
, , , ,
. - ,
, .
Cancel (),
, .
, try
, ,
CancelDialog,
Cancel. , Cancel
.
, ,
: ,
, ;
;
? , :
, - , ,
.



. :
,
.

668


.

,
, .

.
.
.

, .
,
-
, ,
. ,
, ,
.


, ,
.
,
, .

.



, .

.


,
.
, .. ,
, . C++
-,
this.

,
,
.

, .

20.

669

.
.
,
.

, , .. ,
,
,
. , ,
catch,
.
,
.
, catch , ,
.
catch, ,
, catch,
catch.
catch, .

, , ,
..
, ,
.


?
?

.
. ,
, .
? ?
,
.
.

, ?
?
, C++
. ,
. ,
, ,
. ,
.

670

, ,
.

try,
?
, ,
, .

,
cout flifdef debug?

, ,
.
,
.


, ,
. ,
.
,
.


1. ?
2. t ?
3. catch?
4. ?
5. ?
6. ?
7. catch ,
?
8. catch,
, , ?
9. catch (... )?
10. ?

1. try catch
.
2. , 1, -
catch.

20.

671

3.

4.

, 2.
catch ,
, .
3, .

5. : ?
include "string" //
class xOutOfMemory

{
public:
xOutOfMemory(){ theMsg = new char[20];
strcpy(theMsg, "error in memory");}
"xOutOfMemo ry(){ delete [] theMsg; cout
"Memory restored, " endl; }
char * MessageO { return theMsg; }

private:
char * theMsg;
> ;
main()
{
try
{
char * var = new char;
if ( var == 0 )

<
xOutOfMemory * px =
new

xOutOfMemory;

throw px;

}
}
catch( xOutOfMemory * theExceptlon )

{
cout theException->Message() endl;
delete theExceptlon;

)
return 0;

}
6.

,

. ,
If (var 0) if (1), .

672


!
C++.
C++,
.
, C++.
C++.
.
,
. , :

C++


,
, (#).
,
.
, ,
.
,
.
include: ,
, .
:
, , ,
.

21.

673


,
, .
, .
,
, , .

define
def

ine

define BIG 512

, BIG 512
. C + + . 512
, BIG.
, ,
, - . ,

define BIG 512
int myArray[BIG];

, , :
int myArray[512];

, define.
,
.

#define
define - .
, define
.
, , define
const.

define
#define ,
. , :
define BIG

, BIG,
.
, ifdef ( ) ifndef ( ).

674

#endif,
( ).
#ifdef , ,
. :

ffifdef DEBUG
cout << " DEBUG ";

#endif
#ifdef,
, , DEBUG. ,
#ifdef true, ,
#else #endif, .
false, ,
#ifdef DEBUG #endif, , ..
,
.
, #ifndef
ttifdef. #ifndef true ,
.

#else
, #else #ifdef
( #ifndef) #endif.
21.1.

21.1. # d e f i n e ___________________ ______________


1:

#define DemoVersion

2:

#define NTJv/ERSION 5

3:
4:

#include <iostream.h>

5:
6:

int main()

7:

8
9: cout "Checking on the definitions of DemoVersion,
NT_VERSION _and WINDOWS_VERSION...\ n";

10
11

12
13
14
15

#ifdef DemoVersion
cout

<<

"DemoVersion

defined.\

<<

"DemoVersion

not

n";

#else
cout

defined.\

n";

#endif

16
17
18
19

20
21

#ifndef NT_VERSION
cout << "NT_VERSI0N not defined!\ n";
tfelse
cout << "NT_VERSI0N defined as: " << NT_VERSI0N endl;
#endif

21.

675

22

ffifdef WINDOWS^VERSION
cout WINDOWSVERSION definod!\ if;
25
#else
26
cout << "WINDOWS_VERSION was not de1ined.\ n";
27
#end.i f

23

24

28
29
30

cout << " Dotie. \ n";


return 0;

31

hecking on the definitions of DemoVersion, NT_VERSI0N_and


WIND0WS_VERSI0N...
DemoVersion defined.
NT_VERSION defined as: 5
WIND0WS_VERSI0N was not defined.
Done.
1 2 DemoVersion NT_VERSI0N,
NT_VERSI0N 5. 11
DemoVersion, ( ),
12
.
17 NT_VERSI0N
#ifndef. , false
20. NT_VERSI0N
5, .. :
cout << " NT_VERSI0N defined as: " << 5 << end]:
, NT VERSION
5, ,
NT_VERSI0N ;
5, ,
.


.
,

, 23 WIND0WS_VERSI0N.
, false
26 .



,
.
( . )
( . ).

676

main() .,
. obj,
.
,
. ,
. ,

.
, Animal ANIMAL.hpp.
Dog ( Animal), D0G.HPP
ANIMAL, hpp, Dog
Animal. Cat ANIMAL, hpp .
, Cat Dog,
ANIMAL, hpp.
,
Animal, .
. ANIMAL
:
.

ifndef ANIMAL.HPP
define ANIMAL.HPP
//
#en

dif

: ANIMAL.HPP ,
, .
define #endif
.
,
, , , ..
ANIMAL.HPP.
define , .
ANIMAL,HPP ,
, FALSE, ANIMAL, hpp
.
eise ( ) endif (
). ,
.
( ANIMAL.HPP),
, , (.),
, .
, ,
.

. ,
.

21.

677


define .
, define.
.
. , TWICE :
define TWICE(x) ( () * 2 )

:
TWICE(4)

TWICE(4) , 8!
4, : ((4) * 2),
4 * 2 8.
,
.
MIN:
define (,) ( () > () ? () : () )
define MIN(, ) ( () < () ? () : () )

,
, ..
. , ,
.

define (,) ( () > () ? () : () )


int = 5, = 7, z;
z = (,);

:
int = 5, = 7, z;
z =

(,) (

() > () ? () : () )(,)

, , ..
(, ) ( () > () ? () : () ),
(, ).
(,)
-:

int = 5, = 7, z;
z =7;

amu
,
. ,
,

678

#!11 (,) > ? :

5 7, .
, ,
21.2.

21.2. _______________________
1:// 21.2.
2:
include <iostream.h>

3:
4:

define CUBE(a) ( (a) * (a) * (a) )

5:

define THREE(a) a * a * a

6:
7:

int main()

8:

9:
10:

long x = 5;
long = CUBE(x);

11:

long z = THREE(x);

12 :
13:
14:

cout << ": " << << endl;


cout << "z: " << z << endl;

15:
16:

long a = 5, b = 7;

17:

= CUBE(a+b);

18:

z = THREE(a+b);

19:
20:

cout << ": " << << endl;

21:

cout << "z: " << z << endl;

22:

return 0;

23:

' y: 125
z: 125
y: 1728
z: 82

4 CUBE ,
. 5
THREE, .
5,
. CUBE(5)
( (5) * (5) * (5) ), 125,
THR(5) 5 * 5 * 5 , 125.
1618
5 + 7. CUBE(5+7) :
( (5+7) * (5+7) * (5+7) )

21.

679


( (12) * (12) * (12) )
THREE(5+7)

7*5

7*5

1728.


, :
5

(7

5)

(7

5) +

(35)

(35) + 7

82.


C++ .
,
. ,
(\),
.
,
. ,
12 ,
( , ). ,
, ,
, .
,
, , ,
,
. .
:
.
,
C++ C++.
,
, 19.


. ,
21.3 CUBE, ,
CUBE 21.2, ,
.

680

21.3.
1:

include ciostream.h>

2:
3: inline unsigned long Square(unsigned long a) { return a * a; }
4:

inline unsigned long Cube(urisigned long a)

5:

{ return a * a * a; }

6:

int main()

7:

8:

unsigned long x=1 ;

9:

for (;; )

10 :
11:

cout << "Enter a number (0 to quit):

12:

cm >> x;

13:

if (x == 0)

14:

break;

15:

cout << "You entered: " << x;

16:

cout << Square(" << x << "): ";

17 :

cout << Square(x);

18:

cout<< Cube(" << x << "): ";

19:

cout << Cube(x) << << endl;

20:

21 :

return 0;

22:

>

RWMWwaswifa; _ ,
; ( ,i Enter a number (0 to quit)
fib t' 1 I1.1' It 1 ^ 1 1 'f .. . , .. / -1 \
You entered: 1. Square(l)
Enter a number (0 to quit)
You entered: 2. Square(2)
Enter a number (0 t.o quit.)
You entered: 3. Square(3)
Enter a number (0 to quit)
You entered: 4. Squa r e(4)
Enter a number (0 to quit)
You entered: 5, Squaie(5)
Enter a number (0 to quit.)
You entered: 6. Square(6)
Enter a number - (0 to quit)

1
1. Cube(1): 1.
2
4. Cube(2): 8
3
9. Cube(3): 27.
4
16. Cube(4): 64.
5
25. Cube(5): 125
6
36. Cube(6): 216,
0

3 4 : 8()

, , ,
, ,
, .
,
, (, 17).
,
, .
.

21.

681

17 Square, 19 Cube. , ,
:
16: cout << ". Square(" << << "): " << * << ". Cube (" << << "): << * *
"." endl;



. (#) ,
. (##) .



. ,
define WRITESTRING(x) cout << #

:
WRITESTRING(This is a string);

:
cout << "This is a string";

,
cout.

This

is

string

.
,
, , ,
.
, ,
fOnePrint, fTwoPrint, fThreePrint, fFourPrint fFivePrint.
:
#define fPRINT() f ## ## Print

fPRINT() Two,
fTwoPrint, Three, fThreePrint.
Partslist.
List. ,

, , ..
AnimalList,
CarList, ComputerList .
,
, , .

682

, ,
. , :
define Listof(Type) class Type##List \

{\
public: \
Type##List(){ } \
private:

int itsLength; \

}:
,
. (AnimalList),

Listof(Animal)

AnimalList.
,
19.

, __DATE__,

, ,
, .
,
. __DATE__ . ____________ TIME__
. _____ LINE_____ FILE__
. ,
. , _______________ DATE__
, .
.
__TIME___ ,___ LINE________ FILE___ .

assertQ
assert,
TRUE, TRUE,
, FALSE.
,
(. 20).
assert() ,
, DEBUG.

.
.

21.

683

, ..
assertO, . 21.4
assertO .

21.4. a s s e

r t ( ) ______________________________________________

1: // 21.4. ASSERT
2: define DEBUG
3: include <iostream.h>
4:
5: ifndef DEBUG
6:

define ASSERT(x)

7: else
8 :

define ASSERT(x) \

9:

if (! (x)) \

10: { \
11:

cout << "ERROR!! Assert " << x << " failed\ n"; \

12:

cout << " on line " << ____ LINE__ << "\ n"; \

13:

cout << " in file " << ____ FILE__ "\ n"; \

14:

15: endif
16:
17:
18: int main()
19: {
20:
21:

int x = 5;
cout << " assert: \ n";

22:

ASSERT(x==5);

23:

cout "\ assert: \ n";

24:

ASSERT(x != 5);

25:

cout << "\ n,\ n";

26: return 0:
27: }

, A-

First assert:

Second assert :
ERROR!! Assert

x !=5

failed

on line 24
in file test1704,cpp
Done,

2 DEBUG.
,.,
^ 0 ( )
, . 8-14
assertO. , ASSERT, hpp,
.
5 DEBUG. ,
assertO , .
DEBUG , 8-14.

684

assert() ,
. 9 , .
FALSE, ( 11 13).
TRUE, .

assorti]
, ,
, ,
, ,
, ,
. - ,
,
, .
,
. ,
, ,
. ,
,
assert() , .
a;.si )
, ,
DEBUG. , a;,m i )
,.
, .

assert()
,
. , assert()
, ,
, .,
. assoit()
. , assertO
, .
, assertO
.
assertO, .
assertO
:
Animal *pCat = new Cat ;
Assert(pCat); //

pCat->SomeFunction() ;

.
assertO
.
, assert()B
.
, , ,

21.

685

NULL ( ).
, ,
NULL. , pCat->SomeFunction(),
.
NULL
, .
, . , assert()
, DEBUG . (
20.)
new

assert()


,
assert(). - ,
, assert()
, . ,
ASSERT ( = 5)

, == 5,
.
, assertO ,
0. , ,
5.
5.
TRUE, = 5 5,
5, 5 ,
.
assertO
5, ,
. . assertO
5.
0, .
,
, - ! .
, ,
. ,
,
.


,
- .
. ,
: CIRCLE
ANIMAL 100.
Invariants(),
TRUE ,
. ASSERT(InvariantsO)

686

. , InvariantsO
TRUE .
InvariantsO 21.5.

21.5. l n v a r i a n t s ( ) ______________________
1: #define DEBUG
2: define SHOW_INVARIANTS
3: include <iostream.h>
4: include <string.h>
5:
6: #ifndef DEBUG
7: define ASSERT(x)
8: else
9: define ASSERT(x) \
:

if (! (x)) \

11: < \
12:

cout << "ERROR!! Assert " << #x << " failed\ n"; \

13:

cout << " on line " << ____ LINE__ << "\ n"; \

14:
15:

cout << " in file " << ____ FILE__ << "\ n"; \
}

16: endif
17:
18:
19: const int FALSE = 0;
20: const int TRUE = 1;
21: typedef int bool;
22:
23:
24: class String
25: {
26:
27:

public:
//

28:

StringO;

29:

String(const char const);

30:

String(const String &);

31:

'StringO;

32:
33:

char & operator[](int offset);

34:

char operator[](int offset) const;

35:
36:

String & operator= (const String &);

37:

int GetLen()const { return itsLen; }

38:

const char * GetStringO const { return itsString; }

39:

bool InvariantsO const;

40:
41:
42:
43:
44:

private:
String (int);
char * itsString;

//

// itsLen;

21.

687

int itsLen;

45:
46:

};

47:
48:
49:

//

50:

<

String::St ring()

51:

itsString = new char[1 ];

52:

itsString[0] = 1\ O;

53:

itsLen=0;

54:

ASSERT(InvariantsO);

55:

56:
57:

// () ,

58:

//

59:

// , .

60:

String::St ring(int len)

61:

62:
63:
64:

itsString = new char[len+1];

65:

itsLen=len;

for (int i = 0; i<=len; i++)


itsString[i] = '\ 0';

66:
67:

ASSERT(InvariantsO);

68:

69:

// String

70:
71:

String::St ring(const char * const cString)

72:

itsLen = strlen(cString);

73:

itsString = new char[itsLen+1];

74:

for (int i = 0; iCitsLen; i++)

75:

itsSt ring[i] = cSt ring[i ];


itsString[itsLen]='\ O';

76:
77:

ASSERT(Invariants());

78:
79:

>

80:

// -

81:

String::String (const String & rhs)

82:

83:

itsLen=rhs.GetLen();

84:

itsString = new char[itsLen+1 ];

85:

for (int i = 0; KitsLen; i++)

86:

itsString[i] = rhs[i ];

87:

itsString[itsLen] = 1\ O;

88:

ASSERT(InvariantsQ);

89:
90:

91:

// ,

92:

String::'String ()

93:

94:

ASSERT(Invariants());

95:

delete [] itsString;

96:

itsLen = 0;

97:

>

98:
99:// ,
100: // ,
101: String& String::operator=(const String & rhs)

102:

103:

ASSERT(InvariantsO);

104:

if (this == &rhs)

105:

return *this;

106:

delete [] itsString;

107:

itsLen=rhs.GetLen();

108:

itsString = new char[itslen+1];

109:

for (int i = 0; KitsLen; i++)

110:
111:

itsSt ring[i] = rhs[i];


itsString[itsLen] = \ O';

112:

ASSERT(InvariantsO);

113:
114:

return this;
}

115:
116: //
117:

char & String::operator[](int offset)

118:

119:

ASSERT(InvariantsO);

120;

if (offset > itsLen)

121:

122:

ASSERT(InvariantsO);

123:

return itsString[itslen-1];

124:

>

125:

else

126:
127:

{
ASSERT(Invariants());

128:

return itsString[offset];

129:

130:
131:

}
//

132:

char String::operator[](int offset) const

133:
134:

{
ASSERT(Invariants());

135:

char retVal;

136:

if (offset > itsLen)

137:

retVal = itsString[itsLen-1];

138:

else

139:

retVal = itsString[offset];

140:

ASSERT(Invariants());

141:

return retVal;

142:

143:

bool String::Invariants() const

144:

21.

145:

#ifdef SHOW_INVARIANTS
cout << "Invariants Tested":

146:
147:

Sendif
return ( (itsLen && itsString) ||

148:

149:
150:
151:

(litsLen && (itsString) );

}
class Animal

152:

153:

public:

154:

AnimalO :itsAge(1), itsName("John Q. Animal")


{ ASSERT(InvariantsQ): }
Animal(int, const String&);

155:
156:

157:

~Animal(){ }

158:

int GetAge() { ASSERT(InvariantsO); return itsAge;}

159:

void SetAge(int Age)

160:

161:

ASSERT(InvariantsO);

162:

itsAge = Age;

163:
164:

ASSERT(InvariantsO);

165:

String& GetNameO

166:
167:

{
ASSERT(Invariants());
return itsName;

168:
169:

170:
171:

void SetName(const String& name)

172:

ASSERT(InvariantsO);

173:

itsName = name;

174:

ASSERT(Invariants());

175:
176:
177:

bool Invariants!);
private:

178:

int itsAge;

179:

String itsName;

180:
181:
182:

Animal::Animal(int age, const String& name):

183:

itsAge(age),

184:

itsName(name)

185:

{
ASSERT(InvariantsO);

186:

187:

188:
189:

bool Animal::Invariants!)

190:
191:

#ifdef SH0W_INVARIANTS

192:
193:

194:

{
cout "Invariants Tested";
#endif
return (itsAge > 0 && itsName.GetLenO);

195: }
196:
197 :

int main( )

198:
199:

Animal sparky(5, "Sparky");

200:

cout << "\ n" << sparky. GetNameO GetStringO << " is
cout << sparky.GetAge() << " years old. ";

201

202:

sparky.SetAge(8);

203:

cout << "\ n" << sparky.GetName().GetString() << " is

204:

cout << sparky.GetAge() << " years old. ";

205:

return 0;

206:

String OK String OK String OK String OK String OK String OK String OK


String OK String OK Animal OK String OK Animal OK
Sparky is Animal OK 5 years old. Animal OK Animal OK
Animal OK Sparky is Animal OK 8 years old. String OK

915 assert(). DEBUG


assert() FALSE, .
39 - InvariantsO String,
143150. 4955,
54, , -
InvariantsO, .
, InvariantsO , .
InvariantsO ,
. : -
.
176 Animal InvariantsO,
189195. 155, 158, 161 163:
InvariantsO.


, assertO

, .
,
. 21.6.

21.. ______________________________________
1: // 21.6.
2: include <iostream.h>
3: define DEBUG
4:

21.

691

5:

#ifndef DEBUG

6:

define PRINT(x)

7:

else

8:

define PRINT(x) \

9:

cout << #x << ":\ t" x << endl;

10:

endif

11:
12:

enum bool { FALSE, TRUE } ;

13:
14:

int main()

15:

16:

int x = 5;

17:

long y = 738981;

18:

PRINT(x):

19:

for (int 1 = 0 ;

i < x; i++)

20: {
21:
22:

PRINT(i);
>

23:
24:

PRINT (y);

25;

PRINT("Hi.");

?6:

int *px = &x;

27:

PRINT(px);

28;

PRINT (*px);

29:

raturn 0;

30:

; 5
:

:
".";
:

73898
.
0x2100

*: 5

PH () ( 510)
. ,
, , .., ,
! "".
":\ ",
.
(),
.
, 0x2100
.

692


, ,
,
( DEBUG).
, ,
, - .
, define DEBUG
. ,
: HIGH (), MEDIUM (), LOW () NONE (). 21.7
, , String Animal 21.5.

21.7. _____________________________________________________
1:

enum LEVEL { NONE, LOW, MEDIUM, HIGH } ;

2:

const int FALSE = 0;

3:

const int TRUE = 1;

4:

typedef int bool;

define DEBUGLEVEL HIGH

include

9:

include <string.h>

<iostream.h>

10
11

#if

12

define ASSERT(x)

13

else

DEBUGLEVEL

<

LOW

14

define ASSERT(x) \

15

if (! (X)) \

16

//

17

cout "ERROR!! Assert " #x " failed\ n"; \

18

cout " on line " ______ LINE__ "\ n"; \

19

cout " in file " ______ FILE__ "\ n"; \

20
21
22

endif

23

if

24

define EVAL(x)

25

else

28:
28

DEBUGLEVEL

<

MEDIUM

define EVAL(x) \

27
27: cout << X ":\ t" x andl;
28:

endif

29:
30:

#if DEBUGLEVEL < HIGH

31 :

define PRINT(x)

32:

else

33:

define PRINT(x) \

34:

cout x endl;

35:

endif

21.

693

36:
37:
38:

class String

39:

40:

public:

41:

//

42:

StringO;

43:

String(const char const);

44:

String(const String &);

45:

StringO;

46:
47:

char & operator[ ] (int offset);

48:

char operator[](int offset) const;

49:
50:

String & operator= (const String &);

51:

int GetLen()const { return itsLen; }

52:

const char GetStringO const

53:

{ return itsString; }

54:

bool InvariantsO const;

55:
56:

private:

57:

String (int); //

58:

char * itsString;

59:

unsigned short itsLen;

60:

} ;

61:
62://
63:

String::St ring()

64:

65:

itsString = new char[1];

66:

itsString[0] = \ O';

67:.

itsLen=0;

68:
69:

ASSERT(InvariantsO);
}

70:
71:// () ,
72:

//

73:

// . Null.

74:

String:;String(int len)

75:

76:

itsString = new char[len+1];

77:

for (int i = 0; i<=len; i++)

78:

itsString[i] = 1\ O';

79:

itsLen=len;

80:

ASSERT(Invariants());

81:

82:
83:

// String

84:

String::String(const char * const cString)

694

85:

86:

itsLen = strlen(cString);

87:

itsString = new char[itsLen+1];

88:

for (int i = 0; i<itsLen; i++)

89:

itsString[i] = cSt ring[i];

90:

itsString[itsLen]=\ O;

91:

ASSERT(InvariantsO);

92:

93:
94:

// -

95:

String::String (const String & rhs)

96:

97:

itsLen=rhs.Getlen();

98:

itsString = new char[itsLen+1];

99:

for (int i = 0; i<itsLen;i++)

100:

itsString[i] = rhs[i];

101:

itsString[itsLen] = \ O;

102:

ASSERT(InvariantsO);

103:

>

104:
105: //
106:

String::'String ()

107:

108:

ASSERT(Invariants());

109:

delete [] itsString;

110:

itsLen = 0;

111 :

112:
113:// ,
114:

//

115: String& String::operator=(const String & rhs)


116:
117:

{
ASSERT(InvariantsO);

118:

if (this == &rhs)

119:

return this;

120:

delete [] itsString;

121:

itsten=rhs.GetLen();

122:

itsString = new char[itsLen+1];

123:

for (int i = 0; i<itsLen;i++)

124:

itsString[i] = rhs[i];

125:

itsString[itsLen] = '\ O;

126:

ASSERT(InvariantsO);

127:

return *this;

128:

129:

'

130:

//

131:

char & St ring::operator[](int offset)

132:

133:

ASSERT(InvariantsQ);

21.

695

134:

if (offset > itsLen)

135:

136:

ASSERT(Invariants());

137:

return itsString[itsLen-1];

138:

else

139:

140:

141:

ASSERT(InvariantsO);
return itsString[offset];

142:
143:
144:

}
}

145:

//

146:

char String::operator[](int offset) const

147:

148:

ASSERT(Invariants());

149:

char retVal;

150:

if (offset > itsLen)


retVal = itsString[itsLen-1];

151:

else

152:
153:

retVal = itsString[offset];

154:

ASSERT(InvariantsO);

155:

return retVal;

156:
157:
158:

bool String::Invariants() const

159:

160:

PRINT("(String Invariants Checked)");

161:
162:

return ( (bool) (itsLen && itsString) ||

163:

(!itsLen && !itsString) );

>

164:
165:

class Animal

166:
167:

public:

168:
169:

{
AnimaK ): itsAge( 1), itsName("John 0, Animal")
{ ASSERT(Invariants());}

170:
171:

Animal(int, const Stringi);

172:

"Animal(){ }

173:
174:
175:

int GetAge()

176:

ASSERT(InvariantsO);
return itsAge;

177:
178:

179:
180:
181:
182:

void SetAge(int Age)

{
ASSERT(Invariants());

183:

itsAge = Age;

184:

ASSERT(InvariantsO);

185:
186:

}
String& GetNameO

187:

188:

ASSERT(InvariantsO);

189:

return itsName;

190:

191:
192:

void SetName(const String& name)

193:

194:

ASSERT(InvariantsO);

195:

itsName = name;

196:

ASSERT(InvariantsO);

197:

198:
199:

bool Invariants!);

200: private:
201:

int itsAge;

202:

String itsName;

203: } ;
204:
205: Animal::Animal(int age, const Strng& name):
206: itsAge(age),
207: itsName(name)
208: {
209:

ASSERT(InvariantsO);

210:}
211:

212: bool Animal::Invariants!)


213: {
214:

PRINT("(Animal Invariants Checked)");

215:

return (itsAge > 0 && itsName.GetLen());

216: }
217:
218: int main()
219: {
220:

const int AGE = 5;

221:

EVAL(AGE);

222:

Animal sparky(AGE,"Sparky");

223:

cout "\ n" sparky.GetName().GetString();

224:

cout " is ";

225:

cout << sparky.GetAge() << " years old.";

226:

sparky.SetAge(8);

227:

cout << "\ n" << sparky.GetName().GetString();

228:

cout << " is ";

229:

cout sparky.GetAge() << " years old.";

230:

return 0;

231: }

21.

697

AGE: 5
(String
(String
(String
(String
(String
(String
(String
(String
(String
(String

Invariants Checked)
Invariants Checked)
Invariants Checked)
Invariants Checked)
Invariants Checked)
Invariants
Checked)
Invariants Checked)
Invariants Checked)
Invariants Checked)
Invariants Checked)

Sparky is (Animal Invariants Checked)


5 years old. (Animal Invariants Checked)
(Animal Invariants Checked)
(Animal Invariants Checked)
Sparky is (Animal Invariants Checked)
8 years old. (String Invariants Checked)
(String Invariants Checked)
// run again with DEBUG = MEDIUM
AGE: 5
Sparky is 5 years old.
Sparky is 8 years old.

1121 assert() ,
, DEBUGLEVEL ,
LOW (.. DEBUGLEVEL NONE). ,
assert() ( 1421). 24 EVAL
, DEBUGLEVEL , MEDIUM; ,
DEBUGLEVEL NONE LOW, EVAL .
, 3035, PRINT ,
DEBUGLEVEL , HIGH. PRINT
, DEBUGLEVEL
HIGH, .. , DEBUGLEVEL
MEDIUM, EVAL assert().
PRINT Invariants()
. EVAL 221,
AGE.


.
,

.

.


,

.

698


, ,
. (, ,
, .,
AlarmState.)
Boolean,
,
.
, long
32 . 1, ,
, 0 . , ,
1,
0. ,
long, .

.

++ .
, ,
. . 21.1.

21.1. ______________________________________________

&

AND ( )

OR ( )

(
(&) ,
.
1, 1, 0,
( ) 0.

()
(|). -
, ,
.
1, ( ) 1.

21.

699

(OR)
().
1, .


(")
. 1010 0011,
0101 1100.


,
. 4-
, ,
128. 128?
128 - 1000 0000 , ,
, 128 .
4- ( ),
128 ,
. , 4-
1010 0110 0010 0110.
128 :
9 8765 4321
1010 0110 0010 0110 // 8-
| 0000 0000 1000 0000 // 128
1010 0110 1010 0110 // 8-

. -, ,
. -, 128 ,
, .. , . -,
1010 0110 0010 0110 .
,
.


,
128 . 128 -
, , 128 (1000 0000),

(0111 1111).
, , .
1010 0110 1010 0110 // 8-
& 1111 1111 0111 1111 // '128 ( 128)

1010 0110 0010 0110 // 8-

700

,
. , 1,
1. - 0, 0.
. , ,
.


,
,
128. :
1010 0110 1010 0110 //
" 0000 0000 1000 0000 // 128
1010 0110 0010 0110 // 8-
"0000 0000 10000000 //128
1010 0110 1010 0110 // 8-


.

.


, ,
.
( Boolean) ,
,
, .
C++
char: .
int,
. , char,
, long - 32 .
?
, .
int.
. ,
. , 1,
0 1. 2,
: 0, 1, 2 3.
..
. 21.8.

21.

701

21.8. ______________________
1:

include ciostream.h>

2:

include <string.h>

3:
4:

enum STATUS { FullTime, PartTime } ;

5:

enum GRADL.EVEL < UnderGrad, Grad } ;

6:
7:

enum HOUSING { Dorm, OffCampus } ;


enum

FOODPLAN

OneMeal,

AllMeals,

WeekEnds,

NoMeals

8:
9:

class student

10:

11:

public:

12:

student():

13:

myStatus(FullTime),

14:
15:

myGradLevel(UnderGrad),
myHousing(Dorm),

16:

myFoodPlan(NoMeals)

17:
18:
19:

{ }
~student(){ }
STATUS GetStatus();

20:
21:

void SetStatus(STATUS);
unsigned GetPlan() { return myFoodPlan; }

22:
23:

private:

24:

unsigned myStatus : 1;

25:
26:

unsigned myGradLevel: 1;
unsigned myHousing : 1;

27:

unsigned myFoodPlan : 2;

28:

} ;

29:
30:

STATUS student::GetStatus()

31:
32:

{
if (myStatus)

33:

return FullTime;

34:

else

35:

return PartTime;

36:

37:

void student::SetStatus(STATUS theStatus)

38:

39:

myStatus = theStatus;

40:

41:
42:
43:
44:

int main()
{

45:

student Jim;

46:
47:

if (Jim.GetStatus()== PartTime)

48:

cout << "Jim is part time" << endl;

702

49:

else

50:

cout "Jim is full time" << endl;

51:
52:
53:

Jim.SetStatus(PartTime);

54:

if (Jim. GetStatusO)

55:

cout << "Jim is part time" << endl;

56:

else

57:

cout << "Jim is full time" << endl;

58:
59:

cout "Jim is on the " ;

60:
61:

char Plan[80];

62:

switch (Jim.GetPlan())

63:

64:

case OneMeal: strcpy(Plan, "One meal"); break;

65:

case AllMeals: strcpy(Plan, "All meals"); break;

66:

case WeekEnds: strcpy(Plan, "Weekend meals"); break;

67:
68:
69:

case NoMeals: strcpy(Plan, "No Meals");break;


default : cout "Something bad went wrong!\ n"; break;
}

70:
71:
72:

cout << Plan << " food plan. " << endl;
return 0;
}

.. . ; - Jim is part time


....... Jim is full time
Jim is on the No Meals food plan.

47 .
student.
928 student. ,
, . ,
(full time) (part time)
. (Unde rGrad).
. ,
.
,
.. ,
, .
- GetStatusO
, .
, .
.
, GetStatusO :
STATUS student::GetStatus()

{
return myStatus;

>

21.

703

. ,
, ,
.
, 47 (full
time part time), .
-:
cout "Jim is " Jim.GetStatusO endl;

:
Jim is

PartTime
.
62
,
70. - , switch
:
case0: st(Plan,"One meal); break;
case

1: strcpy(Plan,"All meals); break;

case2: strcpy(Plan,"Weekend meals); break;


case

3: strcpy(Plan,"No Meals");break;

,
.
, ,
.


,
, ,
.
.
.
,
. ,
, .
,

.
,
, .

. ,
.

704


, ,
C++ . :


.
.
, ;


, , :
if (condition==true)
{
J = k;

SomeFunctionO;
}
m++;


, .
, , ,
. .
, .
( ), ,
.
C++ , , :
, .

switch
switch ,
:
switch{)
{

case _1:
0_1():

break;
case _2:
0_2();

break;
default;
assert ("
break;

'');

21.

705


, ,
. , .

, .

(., ->, [ ]).

,
. : !, ', ++, -,
* ( ), & ( ), sizeof.

: +, =, *, /, %, , , <,
>, ==, !=, &, |, &&, ||,?:, -=, += ..

(4+

, .

3*2).

, if, : if

//.

,
, ..

== ).

char* f;
int& thelnt;

:
char *foo;
int &thelnt;

He .

,
.

, .

(
). C++
,

(), .
() () ,
its - .

(i, , ..) ,
, ,
.

706

,
-.

( )
: SearchQ, ResetQ, FindParagraph(), ShowCursor().
,
: count, state, windSpeed, windowHeight.
: windowlconized, filelsOpen.



. ,
.

,
, SOURCE_FILE_TEMPLATE. ,
, C++ .
.


. , , ,
. -
.


, :

enum TextStyle

{
tsPlain,
tsBold,
tsltalic,
tsllnderscore,

};

.
. ,

. ,
- ( ). ,
, .
, .

, , C++, .. //,
/* */.

,
. ,
, :
++; //

21.

707

, .
. , .
, . ,
( ), , ,
-1, .
, .


. .
, . ,
, .

.
.



. , ,
.

public:, private:
, .

(public) , (protected:),
(private:). - .

(), .
.

-
.
include.

protected:.


, . ,
, .
virtual


, .
.

,
. .


,
, .
include ,
. , ,
.
- ,
, ,
.

708


,
.

assert!)
assertO .
, .
, , .

const
const , : ,
.
, .
(
).
.



++
++. . ,
, ,
,
,
++.
,

. ,
++, , ,
.

|
, , Internet
C++.
C++, ,
.
Internet, C++ (comp. lang.c++
.lang,c++.moderated),
.
, .
( C++),
.

21.

709


, ,
C++. ,
C++ Report SIGS Publications.
, ,
, . (:
,
, . , .)
C++ Report SIGS Publications :
P.O. Box 2031, Langhome, 19047-9700.


,
, . :
jliberty@libertyassociates.com
Web-: www.libertyassociates.com.
.

++.
,

,
++.

++
++.

++
.

.

.
,
, define ifdef.
,
. ,
ifdef, else ifndef, ,
,
.
.
,
.
, .
C++ , ,
, . C++

710

, const ,
.
, ,
- .
, C++,
, C++.


C++ , ,
?
-, C++ ,
C++. -,
C++, .
, ?
,
. ,
, .
, ?
, ,
.
, , .
.

?
watch .
,
.
assertO, ?
- ,

, .
, assertO.
?
.

, .
?
. ,
:
if (){
//
} //

,
.
, ,
,

21.

711

C++
.
.
?
! C++, ... .
, , , ,
. .
, ,
, , ,
. ,
,
.


1. ?
2. ,
, ?
3. define

debug

0 #undef

debug?

4. ?
5.
?
6. & &&?
7. | 11 ?

1. STRING, .
2. assertO,

, ,
2;

( ),
1;

, 0.

3. DPrint, , DEBUG, ,
, , .

4. ,
(+). : !

712

3

,
.
, ; ,
. , ,
, , ++.

catch,

try
.

3.1. , 3
1:

//

2: //

10:

// : PART -

11:

// .

12:

// .

13:
14:

//
//

15:

// ,

16:
17:
18:
19:

//
//
//
//

20:
21:
22:

//
//
//

23: // :

Node - List
List - , ,

Jesse Liberty (jl)

3.

713

24:

II

25:

II : Pentium 200 Pro. 128MB RAM MVC 5.0

26:
27:
28:
29:
30:

II
Il :

31:
32:
33:

//
// : 9/94 - (jl)
//
4/97 - (jl)
// *************************************************
include <iostream.h>

34:
35:

//

36:
37:

class Exception { } ;
class

OutOfMemory

38:
39:

class
class

NullNode : public
EmptyList : public

40:

class BoundsError : public Exception { } ;

41:
42:
43:
44:
45:
46:
47:

II

****************

public

Exception}

Exception} } ;
Exception { } ;

Part * * * * * * * * * * * *

//
class Part
<
public :

48:
49:

Part():its0bjectNumber(1 ) { }

50:
51 :

virtual ~Part(){ } ;
int Get0bjectNumber() const { return itsObjectNumber; }

52:

virtual void DisplayO const =0: //

Part(int ObjectNumber):itsObjectNumber(ObjectNumber){ }

53:
54:
55:
56:
57:
58:

private :
int itsObjectNumber;
} ;
// ,

59:
60:

//
void Part : :Display() const

61:

62:
63:
64:

65:

// << .

66:

// , .

67:

// DisplayO, .

68:

//

69:
70:
71 :

// thePart, C++

cout << "\nPart Number: " << itsObjectNumber << endl;

ostream& operator<<( ostream& theStream,Part& thePart)

72:
73:

{
thePart. DisplayO; // !
return theStream;

74:

7b

75:
76

II **************** rt ************

77:

class CarPart : public Part

78:
79:
80:

{
public:
CarPartO :itsModelYear(94){ }

81:
82:

CarPart(int year, int partNumber);


int GetModelYear() const { return itsModelYear; }

83:
84:
85:

virtual void DisplayO const;


private:
int itsModelYear;

86:
87:

} ;

88:

CarPart::CarPart(int year, int partNumber):

89:
90:

itsModelYear(year),
Part(partNumber)

91:
92:
93:
94:
95:

{ }
void CarPart::Display() const
{
Part::Display();

96:
97:

cout << "Model Year: " << itsModelYear << endl;


}

98:
99:

// **************** AirPlane Part ************

100:

class AirPlanePart : public Part

101:
102:
103:

{
public:
AirPlanePart():itsEngineNumber(1){ } ;

104:

AirPlanePart(int EngineNumber, int PartNumber);

105:
virtual void DisplayO const;
106:int GetEngineNumber()const { return itsEngineNumber; }
107:
108:

private:
int itsEngineNumber;

109:

} ;

110:
111:AirPlanePart::AirPlanePart(int EngineNumber, int PartNumber):
112:
113:

itsEngineNumber(EngineNumber),
Part(PartNumber)

114:
115:

{ )

116:
117:

void AirPlanePart::Display() const


{

118:
Part::Display();
119: cout << "Engine No.: << itsEngineNumber << endl;

120 :

121 :
122:
123:

// List
template <class T>

124: class List;


125:

3.

126:
127:
128:

II **************** Node ************


// ,

II * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:

template <class >


class Node
{
public:
friend class List<T>;
Node (T*);
NodeO;
void SetNext(Node * node) { itsNext = node; >
Node * GetNextO const;
T * GetObjectO const;
private:
T* itsObject;
Node * itsNext;

143:
144:

> ;

145:
146:
147:

// ,..

148:

template <class T>


Node<T>::Node(T* pOjbect):

149:
150:

itsObject(pOjbect),
itsNext(O)

151:

{ }

152:
153:

template <class T>

154:

Node<T>::'NodeO

155:

{
delete itsObject;
itsObject = 0;
delete itsNext;
itsNext = 0;

156:
157:
158:
159:
160:
161:
162:

// NULL,

163:
164:

template <class >


Node<T> * Node<T>::GetNextO const

165:

>

return itsNext;

166:
167:

168:
169:

template <class T>

170:
171:
172:
173:
174:
175:

T * Node<T>::GetObjectO const

176:

{
if (itsObject)
return itsObject;
else
throw NullNode();

177:
178:

// **************** List ************

179:

//

180:

//

181:

jj * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

182:
183:
184:

template <class >


class List
{

185:

public:

186: List();
187: "List();
188:
189: T*

Find(int & position, int ObjectNumber) const;

190: T* GetFirstO const;


191: void Insert(T *);
192: T* operator[](int) const;
193: int GetCountO const { return itsCount; }
194:
private:
195: Node<T> * pHead;
196: int itsCount;
197:
198:
199:
200:

} ;
// ...
template <class T>

201:
List<T>::List():
202: pHead(O),
203:
itsCount(O)
204: { }
205:
206:

template <class T>

207:
List<T>::List()
208:
{
209: delete pHead;
210 :
}

211:
212:
213:
214:

template <class T>


T* List<T>::GetFirst() const
{

215: if (pHead)
216:
217: else

return pHead->its0bject;

218:

throw EmptyList();

219:

220:

221:
template <class T>
222:
T * List<T>::operator[](int offSet) const
223:
{
224: Node<T>* pNode = pHead;
225:
226: if (!pHead)
227:

throw EmptyListQ;

3.

228:
if (offSet > itsCount)

229:

throw BoundsError();

230:
231:
232:

for (int i=0;i<offSet; i++)


pNode = pNode->itsNext;

233:
234:

return pNode->its0bject;

235:
236:
237:

>

238:

// (id)

239:

template <class >

240:

* List<T>::Find(int & position, int ObjectNumber) const

241:

{
Node<T> * pNode = 0;

242:
243:
244:

for (pNode = pHead, position = 0;


pNode!=NULL;
pNode = pNode->itsNext, position++)

245:
246:
247:
248:
249:
250:

{
if (pNode->itsObject->GetObjectNumber() == ObjectNumber)
break;

251:

}
if (pNode == NULL)
return NULL;

252:

else

253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:

return pNode->its0bject;
}
// ,
template <class >
void List<T>::Insert(T* pObject)
{
Node<T> * pNode = new Node<T>(p0bject);
Node<T> * pCurrent = pHead;
Node<T> * pNext = 0;
int New = p0bject->Get0bjectNumber();

265:

int Next = 0;

266:

itsCount++;

267:
268:

if (!pHead)

269:

{
pHead = pNode;
return;

270:
271:
272:
273:
274:
275:
276:
277:
278:

>
// ,
//
if (pHead->its0bject->Get0bjectNumber() > New)
{
pNode->itsNext = pHead;

279:

pHead = pNode;

280:

return;

281: }
282:
283: for (; ; )
284: {
285:

// ,

286:
287:
288:
289:

if (!pCurrent->itsNext)
<
pCurrent->itsNext = pNode;
return;

290:

291:
292:

// , ,

293:

// ,

294:

pNext = pCurrent->itsNext;

295:

Next = pNext->itsObject->GetObjectNumber();

296:
297:
298:
299:
300:
301:
302:

if (Next > New)


{
pCurrent->itsNext = pNode;
pNode->itsNext = pNext;
return;
}
pCurrent = pNext;

303: }
304: }
305:
306:
307: int main()
308: {
309:
310:
311:
312:

List<Part> theList;
int choice;
int ObjectNumber;
int value;

313: Part * pPart;


'314: while (1)
315: {
316:
317:

cout << "(0)Quit (1)Car (2)Plane: ";


cin >> choice;

318:
319:
320:

if (!choice)
break;

321:
322:
323:
324;

cout << " New PartNumber?: ";


cin >> ObjectNumber;

325:
326:
327:
328:

if (choice == 1)
{
cout << "Model Year?: ";
cin value;

329:

try

3.

719

330:
331:
332:
333:
334:
335:
336:
337:
338:
339:
340:

{
pPart = new CarPart(value,ObjectNumber);
}
catch (OutOfMemory)
<
cout << "Not enough memory; Exiting..." << endl;
return 1;
>
}
else
{

341:

cout "Engine Number?:

342:
343:

cin >> value;

344:

try

345:
346:
347:
348:
349:
350:
351:
352:
353:
354:

pPart = new AirPlanePart(value,ObjectNumber);


}
catch (OutOfMemory)
{
cout << "Not enough memory; Exiting..." << endl;
return 1;
}

355:

theList,Insert(pPart);

356:
357:
358:
359:
360:

}
catch (NullNode)

361:

}
catch (EmptyList)

{
cout "The list is broken, and the node is null!" endl;
return 1;

362:
363:

364:

cout "The list is empty!" << endl;


return 1;

365:
366:
367:

368:
369:
370:
371:
372:
373:
374:

}
>
try
<
for (int i = 0; i < theList.GetCount(); i++ )
cout << *(theList[i]);
>
catch (NullNode)
<

375:

cout << "The list is broken, and the node is null!" << endl;
return 1;

376:
377:
378:

}
catch (EmptyList)

379:

380:

cout << "The list is empty!" << endl;

381
382
383

return 1;
catch (BoundsError)

384
385
386
387
388
389

cout << "Tried to read beyond the end of the list!" << endl;
return 1;
return 0;

(O)Quit (1)Car (2)Plane: 1


New PartNumber?: 2837
Model Year? 90
(O)Quit (1)Car (2)Plane: 2
New PartNumber?: 378
Engine Number?: 4938
(O)Quit (1)Car (2)Plane: 1
New PartNumber?: 4499
Model Year? 94
(O)Quit (1)Car (2)Plane: 1
New PartNumber?: 3000
Model Year? 93
(0)Quit (1)Car (2)Plane: 0
Part Number: 378
Engine No. 4938
Part Number: 2837
Model Year: 90
Part Number: 3000
Model Year: 93
Part Number 4499
Model Year: 94

, 3,
, 2.
, ostream
. .
3640 .
.
,
catch, , .

3.

721

,
,
.
45 P a r t , ,
, 2.
o p e r a t o r < < ( ),
( 7074). ,
P a r t , P a r t .
P a r t .
, o p e r a t o r ( )
C a r P a r t A i r P l a n e P a r t .
P a r t ,
C a r P a r t A i r P l a n e P a r t ,
,
. C++.
C++:
.
, , P a r t , .
,
o p e r a t o r - P a r t .
o p e r a t o r - P a r t ,
:
cout << thePart

, c o u t . o p e r a t o r ( P a r t & ) ,
c o u t o p e r a t o r ,
P a r t !
,
o p e r a t o r , P a r t .
D i s p l a y O , -,
.
130143 N o d e . ,
N o d e 2, N o d e
P a r t . ,
.
: N o d e
, ,
175.
182183 L i s t .
,
, , .

.
307308
P a r t , ,
.
C++ ,
, ,
. , 3.2,
, , , C++.

722


, 65-69, , ++
. ?

.

: !

3.2.
#include<iostream.h>
class Animal
{
public:
virtual void Speak() { cout << "Animal
Speaks\ n"; }

class Dog : public Animal


{
public:
void Speak() { cout "Dog Speaks\ n"; }
} ;

class Cat : public Animal


{
public:
void Speak() { cout << "Cat Speaks\ n"; }
} :
void DoIt(Cat*);
void Dolt(Dog*);
int main()
{
Animal * pA = new Dog;
DoIt(pA);
return 0;
}
void DoIt(Cat * c)
{
cout "They passed a cat!\ n" << endl;

3.

723

c->Speak();

}
void DoIt(Dog * d)
{
cout "They passed a dog!\ n" << endl;
d->Speak();
}

C++ .
ttinclude<iost ream. h>
class Animal
{
public:
virtual void Speak() { cout "Animal Speaks\ n"; }
} ;
class Dog : public Animal
{
public:
!

void Speak() { cout << "Dog Speaks\ n"; }

} ;

class Cat : public Animal


{
public:
void Speak() { cout << "Cat Speaks\ n"; }
} ;
void DoIt(Animal*);
int main()
{
Animal * pA = new Dog;
DoIt(pA);
return 0;
}
void DoIt(Animal * c)
{
cout << "They passed some kind of
animal\ n" << endl;
c->Speak();
}

724

, ,
.
,
.
, .
.
. ( 3),
( 14) ( 15)
, .
.

_______________________________________________________

1 (
)

, ; [ ]

3 ()

->

++

++

1,
^ ()

!1[ ]

4
()

,,

* / %

5 ()

6 ()

725


7 ()

, , ,

<<=>>=

8 ()

== \ =

10

11

12

&&

13

II

14

15 ()

*= /=

%=

+= -=

= =

,

17

18

726

&

&= |= ~=
throw

C++


.
, .
, .
.
auto

for

sizeof

break

friend

static

case
catch

goto

struct

if

switch

char

int

template

class

long

this

const

mutable

throw

continue

new

typedef

default

operator

union

delete

private

unsigned

do

protected

virtual

double

public

void

else

register

volatile

enum

return

while

extern

short

float

signed

C++

727

, , ,
. 145,
, .
-
145 , ,
.
3". () 3 ,
.
.
, ,

: , 3, | | |, III ***.
,
1, 2, 3, 4, 5, 6, 7, 8 9. ?
.
.
X. ( )
. ( )
, , ,
. , 15 (
, ), .. 1 5 .
, , .
1. 10 0-9.
2. : (1), (10),

(100) ..
3.

,
99. , ,
0 (-1). ,
0 (103-1), 0-999.


10 ,
10 .
. , 10,
8.

728

1. 8 0-7.
2. : (1),
(8), 64- ..
3. , 0 ( 8 - 1 ) .
, ,
.
10 1510 , .
, 1510 8 178.
, . ,
,
, .
'
17? 1 , 7 7
. .
:
***** *****

:
, .
15 (1 5 ). , -:
**** *******
* * * *

.. : .
178
( ),


15,
16 178, 217.
7 8,
.
- ?
7,
.
, : , ,
, .. ?
: 7, 7, 72, I .. :
4
V
343

3
72
49

2
V
1

1
7
1

. ,
.

7, . ,
. , , 200.

729

,
343, .
, 49 ( )
, 49. 4,
4 ,
4. ,
( ) 0. ,
4 4 , 4 (
). 404,.
968 6
:
54321
64 63 62 61 6

1296 216 36 6 1
968 1296 ( )
, . 968
216 ( ) 4 ,
104. 4. 104 36
( ). 2
32. 2. 32
6 ( ) 5 2. ,
42526, :

5
64
1296
0

4
63
216
4

3
62
36
2

2
61
6
5

1
6
1
2

, ..
(, 6) ,
,
:
4 * 216
2 * 36
5*6
2*1

864
=

=
=

72
30
2
X = 968


2.
: 0 1. :

730

8
27
128

7
26
64

6
25
32

5
24
16

4
23
8

3
22
4

2
21
2

1
2
1

88 ( 2)
. 88 128 ,
0.
88 64 ,
1, 24. 24 32 ,
0.
24 16 ,
1. 8. 8 8 (
) , , 1.
, .

, :
1 * 64 = 64
0 * 32 =
0
1 * 16 = 16
1 * 8 = 8
0 *
0 *
0 *

4 =

2 =

1 =

I =

88

2
2
.
, , ,
, ,
.

(, , , ..),
,
: . ,
, 1 0. 1
, .
.
,
. ,
,
,
.


, ( ).
8 ,
() 8-
, .

731

(4 ) (nybble).

256
. ? .
( 1),
255. , 0, ..
255 256 .


, 210 (1 024) 103 (1 ).
, 210
1 (1 ), ,
.
1024 * 1024 (1 048 576) ,
1 (
1 ), 1 024 1 (
, ).



.
.

, .
, Intel 80.6 1001 0101
. 149,
, , .
, ,
. ASCII.
7- .
, 0110 0001.
97 (64 + 32 + 1), ,
, . , ASCII
97, 97
(0110 0001) .


,

. ,

, . ?
, .

732

16 : 0, 1, 2, 3,
4, 5, 6, 7, 8, 9, , , , , . , ,
. ,
.
:
4
163
4096

3
162
256

2
161
16

1
16
1


(
). , , 8:
* 256 = 15

* 256

= 3840

8 - 16 =

128

* 1 = 12 *

1 =

12

3840 + 128 +

1 =

3980


, :
* 16 = 15 * 16

240

12

* 1 = 12 * 1 =
240 + 12 =

252

252 :

9
28

8
27

7
2

6
25

5
24

4
2

3
2
2

2
2

1
2
0

256

128

64

32

16

256 .
128
64

124
60

32

28

16

12

2
1
1

1 1 1

, 11111100.
, , ,
, .
1100.
12, .
1111, 10
15, 16 .
, :

733

1111 0000

, FC,
1111 1100.
. ,
,
, . :
1011 0001 1101 0111

,
: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384 32768.
1 x 1 =

1 X 2 =

1 X 4 =

0 x 8 =

1 16 =

16

1 32 =

1 64 =

64

1 128 =

128

1 256 =

256

1 512 =

1 X 1024 =

1 2048 =

1 4096 =

4 096

1 8192 =

8 192

1 16384 =

1 32768 =

32 768

45 527


:
65536

4096

256

16

65 536 ( ) 45 527,
0. 4096 ( )
45 527 471. 471 256 (
) 215. 215 16
( ) 13 7. ,
B1D7.
:
(11) * 4096 =
1

45 056

* 256 =

256

D (13) * 16 =
7

734

208

* 1

7
45 527

1011000111010111, : 1011 0001 1101 0111.


:
1011 =
1x1

1x2

1
2

0x4

1x8 = 8
:

11

:
0001 =
1x1 =

0x2 =

0X4 =

0x8 =

1101 =
1x1

0x2

1
0

1x4

1x8 = 8
:

13

: D
0111

1x1

1x2

1x4

0x8 = 0
:

: 7

, B1D7.

735

^slhI/ws

1

1. ?

.
,
.
2. ?
.
, .
3. ?
,
,
, .
,
.
4. ?
, , , ,
.

1. ,
.
2. , .
3. include #.
4. Hello World,
.

736

2

1. ?
.
,
.
18.
2. mainO?
main() .
3. ?
C++ (//),
.
(/* */), ,
, .
,
.
4. ?
, C++
.
C++, , C++
.
5. ?
.
C++,
(//).

1. , I love C++.
1: include <iostream,h>
2:
3: int main()
4: {
5: cout << "I love C++\n";
6: return 0;
7: }

2. , ,
.
int main() { returna 0; }

3. : . ?
?

737

include <iostream.h>
int main()
{
cout Is there a bug here?'';
return 0;
}

4 .
4. 3, ,
.
include <iostream.h>
int main()
{
cout << " Is there a bug here?"
return 0;

3

1. ( )
?
,
,
.
.
2. unsigned short int long int?
unsigned ,
.
(short) 2 , (long) 4 .
3. ?
, ..
. ,
,
,
.
4. const
define?

, const,
,
. ,

, .

738

5. ?
;
. , () PeopleOnTheBus () , , xjk prndl,
, .
6.

(enum) , Blue?
enum COLOR { WHITE, BLACK = 100, RED, BLUE, GREEN = 300 };
BLUE = 102

7. ,
?
) ;
) ! ;
) R79J , ;
) Totallncome ;
) Invalid , .

1. ?

.
Unsigned short integer

.
unsigned float

Unsigned long integer

.
Unsigned double

.
Unsigned short integer

2. .
) myAge ()
) backYardArea ()
) StarsInGalaxy ()
) averageRainFall ()
3. pi, 3.14159.
const float pi = 3.14159;

4. float , pi.
float myPi = PI;

739

4
1. ?
, .
2. = 5 + 7 ? ?
, 12.
3. 201/4?

50

4.

201 % 4?
1

5. , b int,
:

myAge = 39;
= ++;
b = ++;

niyAge: 41, : 39, : 41


6. 8+2*3?

14
7. if( = 3) if ( == 3)?
3 TRUE.
, 3,
TRUE, 3, FALSE .

8. true false?
) 0

FALSE
)

TRUE
) -1

TRUE
) = 0

FALSE
) == 0 // , 0

TRUE

740


1. if,
,
else.
if ( > )
X = ;
else

// > X II == X
= ;

2. . , .
?
1: include <iostream.h>
2: int mainO
3: {
4: int , b, ;
5: cout << "Please enter three numbers\ n";
6: cout << "a:
7: ein >> a;
8; cout << "\ nb: ";
9: ein b;
10: cout << "\ nc:
11: ein >> ;
12:
13: if ( = (a-b))
14: { cout "a:
15: cout a;
16: cout "minus b:
17: cout b;
18: cout << "equals c:
19: cout << << endl; >
20: else
21: cout << "a-b does not equal c: " endl;
22: return 0;
23: }

3. 2; , .
20, 10 50. , ? ?
20, 10, 50. :
: 20 minus b: 10 equals : 10
? , 13 ,
.

4.

:
1: include <iostream.h>
2: int main()
3: {

a = 1, b = 1, ;

4:

int

5:

if ( = (a-b))

741

6:

cout "The value of is: " << c;

7: return 0;
8: }

5. , , 4.
? ?
6.

5 - ,
(1) b (1) 0. 0 false
(), ,
.

5

1. ?

, .
, .
inline .
,
.
2.

, ,
?
. , .

3. , ?
void.

4. ,
?
, ,
int.
5. ?
, (
). .
6. ?

.
7. ?
.
8. ?
,
. C++
. ,
.

742

9. ?
,
.
10. ?
,
.
C++
.

1. Perimeter,
unsigned long int , unsigned short int.
unsigned long int Perimeter(unsigned short int, unsigned short int);

2.

Perimeter 1.
,
( ).
unsigned long int Perimeter(unsigned short int length, unsigned short int width)
{
return 2*length + 2*width;
>

3. : ?
include <iostream,h>
void myFunc(unsigned short int x);
int main()
{
unsigned short int x, y;
= myFunc(int);
cout << "x: " << x << " : " << << "\ n";
}
void myFunc(unsigned short int x)
{
return (4*x);
>

void,
- . , myFunc
, int.
4. : ?
include <iostream.h>
int myFunc(unsigned short int x);
int main()
<
unsigned short int x, y;
= myFunc(x);

743

cout << "x: " << x << " : " << << "\ n";
>
int myFunc(unsigned short int x);
<
return (4*x);
}

, ,
.
5.

, unsigned short int


.
, ,
-1.
short int Divider(unsigned short int valOne, unsigned short int valTwo)
{
if (valTwo == 0)
return -1;
else
return valOne / valTwo;
>

6. ,
, 5.
, , -1.
include <iostream.h>
typedef unsigned short int USHORT;
typedef unsigned long int ULONG;
short int Divider(
unsigned short int valone,
unsigned short int valtwo);
int main()
{
USHORT one, two;
short int answer;
cout << "Enter two numbers.\n Number one: ";
cin >> one;
cout << "Number two: ";
cin >> two;
answer = Divider(one, two);
if (answer > -1)
cout "Answer: " << answer;

else
cout "Error, can't divide by zero!";
return 0;
>

7. , .
,
, .. 2,
4, 16.

744

include ciostream.h>
typedef unsigned short USHORT;
typedef unsigned long ULONG;
ULONG GetPower(USHORT n, USHORT power);
int main()
<
USHORT number, power;
ULONG answer;
cout << "Enter a number: ";
cin >> number;
cout << "To what power? ";
cin >> power;
answer = GetPower(number, power);
cout << number << " to the " << power << "th power is " << answer << endl;
return 0;
}
ULONG GetPower(USHORT n, USHORT power)
{
if(power == 1)
return n;
else
return (n * GetPower(n,power-1));
}

6

1. ?
(.).
.
2. ?
.
.
3. ?
, ,
. -,
.

4.

(public) (private) ?
- ,
- .

5. - ?
. -, - .
6. - ?

745

- ,
, - ,
.
7.

Cat,
- itsAge?
. -.

8.

! ?
?

, - .

9.

- Meow Cat,
void?
- Meow() Cat,
void, :
void Cat::Meow()

10. ?
.

1.

, Employee ()
-: (), yearsOfService ( ) Salary
().
class Employee
{
int Age;
int YearsOfService;
int Salary;
>;

2. Employee, -
-.
class Employee
{
public:
int GetAge() const;
void SetAge(int age);
int GetYearsOfService() const;
void SetYearsOfService(int years);
int GetSalaryO const;
void SetSalary(int salary);
private:
int Age;
int YearsOfService;
int Salary;
>;

746

3. Employee,
Employee; - age, YearsOfService Salary,
.
int main()
{
Employee John;
Employee Sally;
John.SetAge(30);
John.SetYears0fService(5);
John.SetSalary(50000);
Sally.SetAge(32);
Sally.SetYears0fService(8);
Sally.SetSalary(40000);
cout << "At AcmeSexist company, John and Sally have the same job.\n";
cout "John is " << John.GetAgeO << " years old and he has been with";
cout << "the firm for " << John.GetYearsOfService << " years.\n";
cout << "John earns $" << John.GetSalary << " dollars per year.\n\n";
cout << "Sally, on the other hand is " << Sally.GetAge() << " years old and has";
cout "been with the company " << Sally.GetYearsOfService;
cout << " years. Yet Sally only makes $" << Sally.GetSalaryO;
cout " dollars per year! Something here is unfair.";
return 0;
}

4.

3 Employee,
, , 1
.
float Employee:GetRoundedThousands() const
{
return (Salary+500) / 1000;
>

5. Employee , -
age, YearsOfService Salary .
class Employee
{
public:
Employee(int Age, int yearsOfService, int salary);
int GetAge() const;
void SetAge(int Age);
int GetYearsOfService() const;
void SetYearsOfService(int years);
int GetSalaryO const;
void SetSalary(int salary);
private:

747

int Age;
int YearsOfService;
int Salary;
):

6. : ?
class Square
{
public:
int Side;
}

.
7. : ?
class Cat
{
int GetAge() const;
private;
int itsAge;
};

GetAgeO . :
, .
8. : ?
class TV
<
public;
void SetStation(int Station);
int GetStation() const;
private;
int itsStation;
};
main()
{
TV myTV;
myTV.itsStation = 9;
TV,SetStation(IO);
TV my0therTv(2);
}

itsStation . -.
- SetStation()npHMO
.

. SetStationO

- itsStation,
.

748

7

1. for -?
, , :
for ( = , = 10; < 100; ++, ++)

2. goto?
Goto
. ,
, .
3.

for ,
?
. (FALSE),
for . :
for (int = 100; < 100; ++)

4.

while for?
. .

5. , ? .
. for, while:
for(;;)
<
// !
}
while(1)
{
// !
>

6. ?
.

1.
for (int = 0; < 100; ++)?

100

2. for, 10x10.
for (int = 0; i< 10; i++)
{
for ( int ] = 0; j< 10; j++)

749

cout << "";


cout << "\n";

}
3. for, 100 200 2.
for (int = 100; <=200; +=2)

4. while, 100 200 2.


int = 100;
while ( <= 200)
+= 2;

5. do.. while, 100 200 2.


int = 100;
do
{
+=2;
} while ( <= 200);

6. : :
int counter = 0;
while (counter < 10)
{
cout << "counter: " counter;
>

, counter,
while .
7. : :
for (int counter = 0; counter < 10; counter++);
cout << counter << " ";

,
. , , ,
counter,
.
8. : :
int counter = 100;
while (counter < 10)
{
cout "counter now: " << counter;
counter--;
}

counter 100, ,
, counter 10,
FALSE .
int counter = 5;, ,
.
int signed,
.

750

9. : :
cout << "Enter a number between 0 and 5:
>> theNumber;
switch (theNumber)
{
case 0
do2ero();
//

case 1
case 2

//

case 3

//

case 4

//

case 5
doOneToFive();
break;
default:
doDefault();
break;
}

case 0, , break. ,
.

8

1. ?

(&).
2.

, ,
?
, , ,
(*).

3. ?
, .
4. , , ,
?
, , . ,
, , ,
. (*) ,
, .
5. ?
(*) , ,
. (&)
.

751

6. : const int * ptrOne int * const


ptrTwo?

const int * ptrOne , ptrOne


.
.
int * const ptrTwo , ptrTwo
.
.

1. .

int * ;

int vTwo;
int * pThree = &vTwo;

:
)
)
)

2.

int * ; ;
int vTwo; ;
int * pThree = &vTwo;

, yourAgo unsigned short.


, ?
unsigned short * = &you;

3. you 50.
=50;

4.

int
. . ,
- .
int thelnteger;
int plnteger = &thelnteger;
plnteger = 5;

5. : :
include <iostream.h>
int tnain()
{

int * pint;
pint = 9;
cout << " The value at pint: " << *plnt;

return 0;
}

pint .
- , .
. 9
.

752

6. : :
int mainO
{
int SomeVariable = 5;
cout << "SomeVariable: " << SomeVariable "\ n";
int *pVar = & SomeVariable;
pVar = 9;
cout "SomeVariable: " << *pVar << "\ n";
return 0;
}

, 9 ,
pVar. , 9 pVar,
(*). pVar
,
.

9
1. ?
(), ,
. .
2. , ?

.
3. new, ?
.
4. ?
.
5. ?
,
.
.

1. , int,
int int.
int.
int main()
<
int varOne;
int& rVar = varOne;

753

int* pVar = &varOne;


rVar = 5;
*pVar = 7;
return 0;
}

2.

,
. ,
varOne. varOne 6. ,
varOne 7.
varTwo. ,
varTwo. .
int main()
{
int varOne;
const int * const pVar = &var0ne;
*pVar = 7;
int varTwo;
pVar = &varTwo;
return 0;
>

3. , 2.
? ?

.
4. , .
int main()
{
int * pVar;
*pVar = 9;
return 0;
>

5. 4, .
int main()
{
int varOne;
int * pVar = &var0ne;
*pVar = 9;
return 0;
}

6. , .
((include <iostream.h>
int * Func0ne();
int main()

754

int * pint = FuncOne();


cout << "the value of pint in main is: " << pint endl;
return 0;

int * FuncOneO
{
int * pint = new int (5);
cout << "the value of pint in FuncOne is: " << pint << endl;
return pint;
>

7. 6.
include <iostream.h>
int FuncOneO;
int main()
{
int thelnt = FuncOneO;
cout << "the value of pint in main is: " << thelnt << endl;
return 0;
}
int FuncOneO
{
int * pint = new int (5);
cout << "the value of pint in FuncOne is: " pint << endl;
delete pint;
return temp;
}

8. : ?
1; include <iostream.h>

2
3

class CAT

4
public:

5
6

CAT(int age) { itsAge = age; }

'CAT(){ }

int GetAge() const { return itsAge;}

9:

private:
int itsAge;

10
11 :

12 :

};

13: CAT & MakeCat(int age);


14: int main()
15: {
16:

int age = 7;

17:

CAT Boots = MakeCat(age);

18:

cout << "Boots is " Boots.GetAge() << " years old\ n";

19:

return 0;

20: }
21:
22: CAT & MakeCat(int age)
23: {
24:

CAT * pCat = new CAT(age);

25:

return *pCat;

26: >

MakeCat CAT,
.
, .

9. 8.
1: include <iostream.h>
2:
3: class CAT
4: {
5:

public:

6:

CAT(int age) { itsAge = age; }

7:

'CAT(){ }

8:

int GetAgeO const { return itsAge;}

9:

private:

10:
11:

int itsAge;
} ;

12;
13: CAT * MakeCat(int age);
14: int main()
15: {
16;

int age = 7;

17:

CAT * Boots = MakeCat(age);

18:

cout "Boots is " Boots.GetAge() << " years old\ n";

19:

delete Boots;

20: return 0;
21: }
22:
23: CAT * MakeCat(int age)
24: {
25:

return new CAT(age);

26; }

756

10

1. -,
?
-, ,
.
2. ?
, .
, ,
typedef.
3. -?
, . ,
.
4. ?

, delete ,
.
5. - (=)?
, .
6. this?
-, .
7. ?
.
int,
, , .
8. operator+ short int?
, .
9. C++ operator++ ,
?
, .
, .
10.
?
. ,
.

757


1. SimpleCircle ( )
- itsRadius ().
, , .
class SimpleCircle
. {
public:
SimpleCircle();
"SimpleCircleO;
void SetRadius(int);
int GetRadiusO;
private:
int itsRadius;
};

2. , 1, ,
, itsRadius 5.
SimpleCircle::SimpleCircle():
itsRadius(5);
<}

3. ,
itsRadius.
SimpleCircle::SimpleCircle(int radius):
itsRadius(radius)
{}

4.
SimpleCircle itsRadius.
const SimpleCircle& SimpleCircle::operator++()
{
++(itsRadius);
return *this;
>
// Operator ++(int).
// ,
const SimpleCircle SimpleCircle::operator++ (int)
// SimpleCircle
this
SimpleCircle temp(*this);
++(itsRadi us);
return temp;
}

5.

SimpleCircle , itsRadius
.

758

class SimpleCircle
{
public:
SimpleCircleO;
SimpleCircle(int);
"SimpleCircle():
void SetRadius(int);
int GetRadiusO;
const SimpleCircle& operator++();
const SimpleCircle operator++(int);
private:
int itsRadius;
};
SimpleCircle::SimpleCircle()
{itsRadius = new int(5);}
SimpleCircle::SimpleCircle(int radius)
{itsRadius = new int(radius);}
SimpleCircle::~SimpleCircle()
{
delete itsRadius;
}
const SimpleCircle& SimpleCircle::operator++()
{
++(*itsRadius);
return this;
}
// Operator ++(int).
// ,
const SimpleCircle SimpleCircle::operator++ (int)
{
//

SimpleCircle

this
SimpleCircle temp(*this);
++(itsRadius);
return temp;
>

6. SimpleCircle -.
SimpleCircle::SimpleCircle(const SimpleCircle & rhs)
{
int val = rhs.GetRadius();
itsRadius = new int(val);
}

7. SimpleCircle .
SimpleCircle& SimpleCircle::operator=(const SimpleCircle & rhs)
<
if (this == &rhs)
return this;
delete itsRadius;
itsRadius = new int;
itsRadius = rhs.GetRadius();
return this;
>

. , SimpleCircle.
, ,
9.
. ,
.
include <iostream.h>
class SimpleCircle
<
public:
//
SimpleCircle();
SimpleCircle(int);
SimpleCircle(const SimpleCircle &);
'SimpleCircle() {}
//
void SetRadius(int);
int GetRadiusO const;
//
const SimpleCircle& operator++();
const SimpleCircle operator++(int);
SimpleCircle& operator=(const SimpleCircle &);
private:
int itsRadius;
>;
SimpleCircle::SimpleCircle()
{itsRadius = new int(5);}
SimpleCircle::SimpleCircle(int radius)
{itsRadius = new int(radius);}
SimpleCircle::SimpleCircle(const SimpleCircle & rhs)
{
int val = rhs.GetRadius();

760

itsRadius = new int(val);

}
SimpleCircle::'SimpleCircle()
{
delete itsRadius;
}
SimpleCircle& SimpleCircle::operator=(const SimpleCircle & rhs)
{
if (this == &rhs)
return *this;
itsRadius = rhs.GetRadius();
return *this;
}
const SimpleCircle& SimpleCircle::operator++()
{
++(*itsRadius);
return *this;
>
// Operator ++(int).
// ,
const SimpleCircle SimpleCircle::operator++ (int)
{
// SimpleCircle
*this
SimpleCircle temp(*this);
++(*itsRadius);
return temp;
}
int SimpleCircle::GetRadius() const
{
return *itsRadius;
>
int main()
{
SimpleCircle CircleOne, CircleTwo(9);
CircleOne++;
++CircleTwo;
cout << "CircleOne: " << CircleOne.GetRadius() << endl;
cout << "CircleTwo: " << CircleTwo.GetRadius() endl;
CircleOne = CircleTwo;
cout << "CircleOne: " << CircleOne.GetRadiusO << endl;
cout << "CircleTwo: " CircleTwo.GetRadius() endl;
return 0;
}

9. :
?
SQUARE SQUARE ::operator=(const SQUARE & rhs)
{
itsSide = new int;
itsSide = rhs.GetSideO;
return this;
}

rhs this,
= .
10. :
?
VeryShort VeryShort::operator* (const VeryShort& rhs)
{
itsVal += rhs.GetItsVal();
return *this;
>

operator* ,
VeryShort. :
VeryShort VeryShort::operator+ (const VeryShort& rhs)
<
return VeryShort(itsVal + rhs.GetItsVal());
>

11

1. v-?
V-, ,
C++, .


.
2. ?
, .
delete
.
3. ?
.
4. -?

762

, .
5.

,
?
Base : :FunctionName() ;

6.

,
?
FunctionName{);

7. ,
,
?
, .
8. protected?
(
protected) - .

1. ,
void.
Virtual void SomeFunction(int);

2. Square (), Rectangle


(), , , Shape (),
class Square : public Rectangle
{};

3. , Shape
, Rectangle (length width),
Square (length); Square.
Square::Square(int length):
Rectangle(length, length){}

4. - Square,
3.
class Square
{
public :
// ...
virtual Square * clone() const { return new Square(*this); )
// ...
};

5. : ?
void SomeFunction (Shape);
Shape * pRect = new Rectangle;
SomeFunction(*pRect);

763

, . SomeFunction
Shape. Rectangle,
Shape. Rectangle,
.
Rectangle, SomeFunction,
Rectangle.
6. : ?
class ShapeO
{
public :
ShapeO;
Virtual "ShapeO;
Virtual Shape(const Shape&);
} ;

-.

12

1. SomeArray[25]?
SomeArray[0], SomeArray[24]

2. ?

.
,
.
, , .
SomeArray[2][3][2]

3. ,
2.
SomeAr[2][3][2] = { { {1,2},{3,4},{5,6} } , { {7,8},{9,10},{11,12} } };

4. SomeArray[10][5][20]?
10x5x20=1
5. ,
?
.
.
6. ?

,
.
7. ?
8. .

764


1. ,
.
int GameBoard[3][3];

2. , 0
.
int GameBoard[3][3] = { {0,0,0},{0,0,0},{0,0,0} }

3. Node, .
class Node
{
public:
Node ();
Node (int);
~Node();
void SetNext(Node * node) { itsNext = node; }
Node * GetNextO const { return itsNext; }
int GetVal() const < return itsVal; >
void Insert(Node *);
void DisplayO;
private:
int itsVal;
Node * itsNext;
>;

4. : ?
unsigned short SomeArray[5][4];
for (int i = 0; i<4; i++)
for (int j = 0; j<5; j++)
SomeArray[i][j ] = i+j;

SomeArray 5x4 ,
4x5 .
5. : ?
unsigned short SomeArray[5][4];
for (int i = 0; i<=5; i++)
for (int j = 0; j<=4; j++)
SomeArray[i][j] = 0;

, i < 5, i <= 5.
, i == 5 j == 4, SomeArray
, SomeArray[5][4].

765

13

1. ?
,

.
2. v-ptr?
v-ptr
. , ,
v-ptr,
.
3. ,
RoundRect, Rectangle Circle,
, , Shape.
Shape RoundRect?
Virtual,
Shape: RoundRect
Circle. Virtual ,
Shape.
4. Horse () Bird () Animal
() ,
Animal? Pegasus () ,
Horse Bird, Animal?
Horse Bird
Pegasus , Pegasus,
Animal Horse Bird .

Animal.

5. Vehicle () .
class Vehicle
{
Virtual void Move() = 0;

>

6. ADT
, ,
?
,
,
.
.

766


1. JetPlane ( ),
Rocket () Airplane ().
class JetPlane : public Rocket, public Airplane

2. JetPlane, , 747.
class 747 : public JetPlane

3.

, ( ) Bus
() Vehicle (). Vehicle
. Bus
.
class Vehicle
{
virtual void Move() = 0;
virtual void Haul() = 0;
};
class Car : public Vehicle
{
virtual void Move();
virtual void Haul();
};
class Bus : public Vehicle
{
virtual void Move();
virtual void Haul();
};

4. ,
ADT, : SportsCar (
), Wagon () Coupe ( -).
, Vehicle,
.
class Vehicle
(
virtual void Move() = 0;
virtual void Haul() = 0;
};
class Car : public Vehicle
{
virtual void Move();
};
class Bus : public Vehicle
{
virtual void Move();

767

virtual void Haul()

class SportsCar : public Car


{
virtual

void

Haul();

class Coupe : public Car


{
virtual void Haul();

14
1. - ?
. -,
-.
- ,
.
2. -.
static int itsStatic;

3. .
static int SomeFunction();

4. , int
long.
long (* function)(int);

5. , 4, - .
long ( Car::* function)(int);

6. , 5.
long ( Car::* function)(int) theArray [10];

1. ,
- -. ,
- -. ,
.

768

1: class myClass
2: {
3: public:
4:

myClassO;

5:

'myClassO;

6: private:
7:

int itsMember;

8:

static int itsStatic;

9: };
10 :
11: myClass: :myClassO :
12: itsMember(l)
13: {
14:

itsStatic++;

15: >
16:
17: myClass:: myClassO
18: {
19:

itsStatic--;

20: }
21:
22: int myClass::itsStatic = 0;
23:
24: int mainO
25: {}

2. 1,
, ,
- - .
-.
1:

include <iostream.h>

2:
3:

class myClass

4:

5:

public:

6:

myClassO;

7:

"myClassO;

8:

void ShowMemberO

9:

void ShowStaticO;

10:

private:

11:

int itsMember;

12:

static int itsStatic;

13:

};

14:
15:

myClass::myClass():

16:

itsMember(l)

17:

18:

itsStatic++;

769

19

20
21
22

myClass::'myClass()

23

itsStatic--;
cout << "In destructor. ItsStatic: " itsStatic << endl;

24
25
26
27

void myClass::ShowMember()

28
cout "itsMember: " << itsMember << endl;

29
30
31

void myClass::ShowStatic()

32
33

cout << "itsStatic: " << itsStatic << endl;

34
35
36

int

myClass::itsStatic

0;

37
38

int main()

39

<

40

myClass

41

objl.ShowMember();

objl;

42

obj1.ShowStatic();

43
44

myClass obj 2;

45

obj2.ShowMember();

46

obj2.ShowStatic();

47
48

myClass

49

obj3.ShowMember();

50
51

ob]3;

obj3.ShowStatic();
return 0;

52

3. 2 ,
- -.
- .
include <iostream.h>
class myClass
<
public:
myClass();
~myClass();
void ShowMember();
static int GetStaticO;

770

10: private:
11:

int itsMember;

12:

static int itsStatic;

13: };
14:
15: myClass::myClass():
16: itsMember(l)
17: {
18:

itsStatic++;

19: }
20:
21: myClass::'myClass()
22: {
23:

itsStatic--;

24: cout << "In destructor. ItsStatic: " itsStatic endl;


25: }
26:
27: void myClass::ShowMember()
28: {
29:

cout << "itsMember: " << itsMember << endl;

30: }
31:
32: int myClass::itsStatic = 0;
33:
34: void myClass::GetStatic()
35: {
36:

return itsStatic;

37: }
38:
39: int main()
40: {
41:

myClass obj1;

42:

obj1.ShowMember();

43:

cout << "Static: " << myClass::GetStatic() << endl;

44:
45:

myClass obj2;

46:

obj2.ShowMember();

47:

cout "Static: " myClass::GetStatic() << endl;

48:
49:

myClass obj3;

50:

obj 3.ShowMember();

51:

cout "Static: " << myClass::GetStatic() << endl;

52: return 0;
53: }

4. 3 -
-
.

771

1:

include <iostream.h>

2:
3:

class myClass

4:

<

5:

public:

6:

myClass();

7:

'myClass();

8:

void ShowMember();

9:
10

static int GetStatic();


private:

11

int itsMember;

12

static int itsStatic;

13
14
15
16

myClass::myClass():
itsMember(1)

17
18

itsStatic++;

19

20
21

myClass::'myClass()

22
23

itsStatic--;

24

cout << "In destructor. ItsStatic: " << itsStatic << endl;

25
26
27

void myClass::ShowMember()

28
29

cout "itsMember: " << itsMember << endl;

30
31
32

int myClass::itsStatic = 0;

33
34

int myClass::GetStatic()

35
36

return itsStatic;

37
38
39

int main()

40
41

void (myClass::*PMF) ();

42
43

PMF=myClass::ShowMember;
myClass obj1;
(obj1.*PMF)();
cout << "Static: " << myClass::GetStatic() << endl;

48
49

myClass ob]2;

50

(obj2.*PMF)();

51

cout << "Static;

<< myClass: :GetStatic() <<

52
53

myClass obj3;

54

(obj 3.*PMF)();

55

cout << "Static:

56

return 0;

57

>

myClass:

:GetStatic() <<

5. -
. , .
-
. -.
1:

include <iostream.h>

2:
3:

class myClass

4:

5:

public:

6:

myClass();

7:

"myClassO;

8:

void ShowMember();

9:

void ShowSecond();

10:

void ShowThird();

11:
12:

static int GetStaticO;


private:

13:

int itsMember;

14:

int itsSecond;

15:

int itsThird;

16:

static int itsStatic;

17:

18:
19:

myClass: :myClassO

20: itsMember(1),
21: itsSecond(2),
22: itsThird(3)
23:

24:
25:

itsStatic++;
}

26:
27:

myClass: :myClassO

28:

29:

itsStatic--;

30:

cout << "In destructor. ItsStatic: " << itsStatic << endl;

31:

32:

773

33

void myClass::ShowMember()

34
cout << "itsMember: " << itsMember << endl;

35
36
37
38

void myClass:: ShowSecondO

39

40

cout "itsSecond: " << itsSecond << endl;

41
42
43

void myClass::ShowThird()

44

{
cout << "itsThird: " << itsThird << endl;

45
46
47

}
int myClass::itsStatic = 0;

48
49

int myClass::GetStatic()

50

51

return itsStatic;

52
53
54

int main()

55
56

void (myClass::*PMF) ();

57
58

myClass objl;

59

PMF=myClass::ShowMember;

60

(objl.*PMF)();

61

PMF=myClass::ShowSecond;

62

(obj1.*PMF)();

63

PMF=myClass::ShowThird;

64

(obj1.*PMF)();

65

cout << "Static: " << myClass::GetStatic() << endl;

66
67

myClass obj2;

68

PMF=myClass::ShowMember;

69

(obj 2.*PMF)();

70

PMF=myClass::ShowSecond;

71

(obj2.* PMF)();

72

PMF=myClass::ShowThird;

73

(obj 2.*PMF)();

74

cout "Static: " << myClass::GetStatic() << endl;


myClass obj3;
PMF=myClass::ShowMember;
(obj 3.*PMF)();
PMF=myClass::ShowSecond;

80:

(obj3.*PMF)();

81:

PMF=myClass::ShowThird;

82:

(obj 3.*PMF)();

83:

cout << "Static: " << myClass::GetStatic() << endl;

84:

return 0;

85:

16

1. , ?
.
2.

,
- ?
.

3. ?

- .
.
.

4.


?

.
.

5. -?
,
.
6. -?
, ,
.
7.

Dog , , Dog?
, .

8.

Dog Boy, a Terrier Dog,


Terrier ?

, .
9.

Dog , House, Dog


House?
, .

775

10. -?
. ,
public:, protected: private:.

1. Animal (), -,
String.
class Animal :
{
private:
String itsName;
};

2. BoundedArray, .
class boundedArray : public Array
<
//
}

3. Set, BoundedArray.
class Set : private Array
//

4.

15.1 , String
().
include <iostream.h>

include <string.h>

3
4

class String

public :

//

StringO;

9:
10
11

String(const char const);


String(const String &);
"StringO;

12
13

//

14

char & operator[](int offset);

15

char operator[](int offset) const;

16

String operator+(const String&);

17

void operator+=(const String&);

18

String & operator= (const String &);

19

friend ostream& operator

776

20:

( ostream& _theStream,String& theString);

21:

friend istream& operator>>

22:

( istream& _theStream,String& theString);

23:

//

24:

int GetLen()const { return itsLen; }

25:

const char * GetStringO const { return itsString; >

26:

// static int ConstructorCount;

27:
28:

private:

29:

String (int);

30:

char * itsString;

//

31:

unsigned short itsLen;

32:
33: };
34:
35:

ostream&

operator(

ostream&

theStream,String&

theString)

36: {
37:

theStream << theString.GetString();

38:

return theStream;

39: }
40:
41:

istream&

operator>>(

istream&

theStream,String&

42: {'
43:

theStream >> theString.GetStringO;

44:

return theStream;

45: }
46:
47: int main()
48: {
49:

String theString("ripnBeT, .");

50:

cout << theString;

51: return 0;
52: }

5. : ?
1: include <iostream.h>
2:
3: class Animal;
4:
5; void setValue(Animal& , int);
6:
7:
8: class Animal
9: {
10: public:
11:

int GetWeight()const { return itsWeight; }

12:

int GetAgeO const { return itsAge; }

theString)

13: private:
14:

int itsWeight;

15:

int itsAge;

16: > ;
17:
18: void setValue(Animal& theAnimal, int theWeight)
19: {
20:

friend class Animal;

21:

theAnimal.itsWeight = theWeight;

22:}
23:
24: int main()
25: {
26:

Animal peppy;

27:

setValue(peppy,5);

28: return 0;
29: }

friend .
.
6.

, 5, .
1: include <iostream.h>
2:
3: class Animal;
4:
5: void setValue(Animal& , int);

6:
7:
8: class Animal
9: {
10: public:
11:

friend void setValue(Animal&, int);

12:

int GetWeight()const { return itsWeight; }

13:

int GetAge() const { return itsAge; }

14: private:
15:

int itsWeight;

16:

int itsAge;

17: };
18:
19: void setValue(Animal& theAnimal, int theWeight)

20:

21:

theAnimal.itsWeight = theWeight;

22:}
23:
24: int main()
25: {
26:

778

Animal peppy;

27:

setValue(peppy,5);

28: return 0;
29: }

7. : ?
1: include <iostream.h>

2:
3: class Animal;
4:
5: void setValue(Animal& , int);
6: void setValue(Animal& ,int,int);
7:
8: class Animal
9: {
10: friend void setValue(Animal& ,int);
11: private:
12:

int itsWeight;

13:

int itsAge;

14: } ;
15:
16: void setValue(Animal& theAnimal, int theWeight)
17: {
18:

theAnimal.itsWeight = theWeight;

19: }
20:
21:
22: void setValue(Animal& theAnimal, int theWeight, int theAge)
23: {
24:

theAnimal.itsWeight = theWeight;

25:

theAnimal.itsAge = theAge;

26: }
27:
28: int main()
29: {
30:

Animal peppy;

31:

setValue(peppy,5);

32:

setValue(peppy,7,9);

33: return 0;
34: }

setValue(Animal&

int)

setValue(Animal& , int, int) .


8. , 7, .
1: include <iostream.h>

2:
3: class Animal;
4:

779

5: void setValue(Animal& , int);


6: void setValue(Animal& ,int,int);
7:
8: class Animal
9: {
10; friend void setValue(Animal& ,int);
11: friend void setValue(Aninal& ,int,int); // !
12: private:
13:

int itsWeight;

14:

int itsAge;

15: } ;
16:
17: void setValue(Animal& theAnimal, int theWeight)
18: {
19:

theAnimal.itsWeight = theWeight;

20 : }
21:
22:
23: void setValue(Animal& theAnimal, int theWeight, int theAge)
24: {
25:

theAnimal.itsWeight = theWeight;

26:

theAnimal.itsAge = theAge;

27: }
28:
29: int main()
30: {
31:

Animal peppy;

32:

setValue(peppy,5);

33:

setValue(peppy,7,9);

34: return 0;
35: }

16

1. ?
()
.

ist

ream

2. ?
()
.

ostream

3. ein.get()
.

780

- get

() .

. EOF
(end ofyile, .. ).
- ein.get()
.