You are on page 1of 687

.

e

, ,




Herbert Schildt

Teach
Yourself
C++
Third Edition

Osborne McGraw-Hill

C++
3-

-
-
2003

681.3.06
.
C++: . . 3- . .: -, 2003. 688 .
ISBN 5-7791-0086-1

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

681.3.06
:

Authorized translation from the English language edition published by Osborne McGraw-Hill. Copyright (998.
A l l rights reserved. No part of mis book may be reproduced or transmitted in any form or by any means, electronic
or mechanical, including photocopying, recording or by any information storage retrieval system, without permission
in writing from the Publisher. Russian language edition published by BHV St. Petersburg. Copyright 1998.
, Osborne McGraw-Hill. Copyright 1998.
.
, ,
, .
BHV--. Copyright 1998.

NB 02429 24.07.00. 25.06.03.


70*100'/1. . . . . 55,5.
. 3000 . No 942
"6-", 198005, -, ., 29.
, * 77.99.02.953..001537.03.02
13.03.2002 . .

""
199034, -, , 12.
ISBN 0-07-882392-7 (.)
ISBN 5-7791-0086-1 (.)

1998 by Osborne McGraw-Hill


" - -", 199



C++ .
C++ (Object Oriented Programming, OOP).
, C++ OOP
, ,
, . C++
, ,
. ,
.
C++ - AT&T
Bell Laboratories (-, ) 1979 .
" " C++ 1983 .
1980 C++ : 1985
1990 . , C++. C++.
ANSI (American National Standards
Institute, ) ISO
(International Standards Organization, ) C++. 25 1994 . ANSI/ISO C++ (
)
,
. ,
C++.

, : (Standard
Template Library, STL). ,
,
.
,
.
ANSI/ISO
C++, C++
. , -

C++


C++.
, C++
, , . , . ANSI/ISO
,
.
C++- . C++.
C++ (Standard C++).
ANSI/ISO
. ,
, , ,
.


" C++".
, . (Run-Time Type Identification, RTTI)
, . . , C++
.
,
/ C++. , " C++" .

Windows
Windows,
Windows, C++ --
, . C++ Windows. ,
, . ,
. :
Windows .
, Windows
50 70 .
C++
. , Windows .

7_

, Windows,
.
C++,
Windows. , C++ Windows ,
, MFC (Microsoft Foundation Classes), . ,
Windows
, Visual C++ 5 Borland C++ 5. , ,
. ,
Windows,
C++.


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


, D
, Internet http://www.osborne.com.
.

C++

C++ -- . C++ ,
, -
(Object Oriented Programming, OOP). C++
, - ", ",
C++ . , , C++,
. C++
.
C++. ,
, .
, . C++ , . ,
C++ . C++,
.
.
C++. C++
, , . - , , , C++, .
C++ -
, OOP. ,
C++ OOP.
, C++ - . , C++,
.
C++ . -

10

C++

C++ (Standard C++). Standard C++,


, .
C++,

C++. C++,
. C++ - ,
C++, .
, C++. ,
C++ . ,
, C++ mainQ. C++ argc,
argv, . C++ , . C++
, .
, , . ,
, C++.
, .

, ,
, C++. , . (-
.)
, , ,
.

1.1. -
?
- .
.
, -

1. C++

/_

. . ,
.
, . 1950 ,
.
,
.
. , ,
, ( ).
1960 (structured programming language). , . ,
, (, , ) GOTO, ,
.
. ,
50 000
.
,
, ,
, . , .
- . OOP
, ,
, . -
. ,
, . , .
OOP, C++, , , .
.

(encapsulation) ,
, , ,
. -

12

C++


; , "
". , (object). , , .
(private)
(public). . ,
, .
, , , , . , ,
.

. , ,
, .
- .
.

(polymorphism) ( polymorphos) ,
, . ,
- ,
.
. ,
, , : abs(),
labs() fabs(). , .
C++ abs(). ( , , .) ,
, ,
. , C++
.
(function overloading).
, " , ". , . , ,
. , , . , , -

1. C++

73

. .
, , , , .
.
,
, . , , +
, ,
. ,
. C++ , , .
(operator overloading),
,

.

(inheritance) ,
. , ,
. ,
(hierarchical classification). . , . , . ,
, , . , , . ,
, .
( ), , , .
, OOP.

1. OOP.
. ,
, , , (,

14

C++

, ). fopen(). , . , ,
. , , C++ .
2. . , . ,
, ,
. ,
( ) , ,
() .
3. . ,
, . ,
.
.

]
1. ,
.

1.2. C++
C++ .
, C++.
,
,
.
C++. , . , . , Standard C++,
(ANSI American National Standards Institute,
; ISO International Standards Organization, ). , Standard C++ ,
C++. Standard C++
C++.
Standard C++. C++,
ANSI/ISO,

1. C++

15_

C++.

Standard C++.
, . , Standard C++ .
Standard C++ C++,
, , C++.
, , , ANSI/ISO .
, . ,
,
,
. , C++ , .
, , ,
.
: (headers) namespace. , C++. ,
.
/*

C++

*/
linclude <iostrearn.h>

int main()
/* */
return 0;

C++ ,
,
Sinclude
iostream.li, / C++.
( C++ , stdio.h .)
, :

16

__

C++

/*
C++ .
namespace
*/
/

ttinclude <iostream>
using namespace std;
int main ( )
{
/* */
return 0 ;

,
. -, ^include
iostream .h. -,
(namespace). , .

C++
,
. #include. , / stdio.h,
:
#include <stdio.h>

stdio.h , /, .
C++
, .
Standard C++ - . Standard C++

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

1. C++

17_

<iostream>
<fstream>
<vector>
<string>

- ^include. ,
.
C++ , - . , , stdio.h ctype.h
. Standard C++
, . C++
.h. , math.h C++ <cmath>, string,h
<cstring>.

, Standard C++. (
, .)
^include .
, .
C++ ,
.
. /:
#include <iostream.h>


iostream.h. , .h , .
, C++ . . .

.
, .


,
std.
(namespace) , , .

(, , ).
std.
. , std , :
using namespace std;

std .
, , .


, C++ , . ,
,
, . namespace - . , ,
#include <iostream>
using namespace std;


^include <iostream.h>

,
.
,
namespace .
.
, namespace. C++ . , ,
, Standard C++.
, .

1. C++

19

]
,
. , ,
C++.
namespace, ,
. , , .

1.3. C++
C++ ,
C++. , , ,
C++. ( , .) C++,
, .
, , C++. C++,
C++.
, C++, , . ,
printfQ scanfQ, - , C++ ,
. C++ / , /. , . , ,
, . C++ ( ),
. C++:
cout " .\";

cout, ,
C++ . stdout
. , / C++ , , .

C++. ,
100.99:
cout 100.99;

20

C++

,
:
cout ;

C++,
.
, .
, num:
int num;
cin num;

, num &.
, scanfQ
. , . C++
. ( ,
C++.)
,
:
cin ;

/ C++
iostream.h.
C++ .


fr

1. , :
^include <iostream>
using namespace std;
int

main()
int i, j ;
double d;

7. C++

21

i = 10;
j = 20;
d = 99.101;

cout
cout
cout
cout
cout

" :
i;
' ';
j;
' ';

cout d;
return 0;

:
: 10 20 99.101

, namespace,
. , .

2. / .
, , 1,
/,
^include <iostream>
using namespace std;
int
{

main()
int i, j ;
double d;
i = 10;
j = 20;

d = 99.101;
cout " : ";
cout i ' ' j ' ' d;
return 0;

22

C++


cout i ' ' j ' ' d;
.
. ,
, ,
--, .
, . , , , .
3. :
^include <iostream>
using namespace std;
int main{)
{
int i ;
cout " : " ;
i;

cout " : " i "\n";


return 0;
:
: 100
: 100
, i.
4. ,
. .
^include <iostream>
using namespace std;
int main(}
{
int i;
float f ;

char s[80] ;
cout " , :
cin i f s;

1. C++

23_

cout " : ";


cout i ' ' f ' ' s;
return 0;

, , . , (, ).

. , :
10 100.12
:
10 100.12

,
. , . ( scanfQ %s.)
5.
. , , <Enter>,
. (
scanf() ,
- .) -
:
ttinclude <iostream>
using namespace std;
int
{

main()
char ch;
cout " , . \";
do {
cout ":";

in ch;
} while (ch !='x');
return 0;

, ,
<Enter>.

24

C++

1.
.
. ( .)
2. .
.
, 0 .
3. .
/ C++.
/*
C++.

V
finclude <stdio.h>
int main(void)
int a, b, d, min;

printf (" :"};


scanf("%d%d", sa, sb);
min = a > b ? b: a;

for (d=2; d<min; d++)


if (((a%d)==0) s& ((b%d)0)) break;
if (d==min) {
printf(" \");
return 0;
printf(" %d\n", d) ;
return 0;
}

1.4. C++
C++ . , , , . . /* */
, C++ .
,
C++, . // . ,
(, /
), .

^ C++

5_

C++ , C++.

1. , , C++:
/ * .

*/
^include <iostream>
using namespace std;
int main ( }
t
int num; // C++

//
cout " :";

cin num;
//
if ( (num%2)==0) cout " \";
else cout " \";
return 0 ;
2. , C++
. , :
/* ,

// .
.
*/
, , "" .

1. , , C++, :
// /* '/

2. 1.3.

26

__

__

C++

1.5. .
, C++ .
.
C++. , C++,
.
class.
.
:
class _. {

public:

} ;

_ .
, , . _ ,
. , _
,
.
, , , , (members) .
, , .
, .
public,
. ,
public, ,
, .
:
class myclass {
//
int a ;
public:
void set_a(int num)
int get_a ( ) ;

, ,
set_a() get_a(). ,

1.

C++

27

. , ,
- (member functions).
, myclass. set_a() get_a() myclass, . , set_a() get__a(),
myclass, ,
myclass.
set_a() get_a() myclass, . - , -, .
. (scope resolution operator). ,
- set_a() get_a():
void myclass : : set_a (int num)

{
a=num;

}
int myclass: :get_a (}

{
return a;

, set_a() get_a() ,
myclass . , set_a() get_a()
myclass,
.
- :
: : ( )

{
. . .//

_ ,
.
myclass myclass,
,
. , , . ,
myclass:
myclass obi, ob2; // myclass

28

C++

,
.
. , , ,

,
, (.), ,
. , , set_a() 2:
obl.set_a(10); // 10
2.set_a(99); // 2 99

, 10 2 99. , . , obi 2.

, .

1. , , myclass, ,
2 :
#include <iostream>
using namespace std;
class myclass {
// myclass
int a;
public:
void set_a{int mini);
int get_a ( ) ;
void myclass: :set_a(int num}
a=num;

1.

C++

29

int myclass: :get_a


{

return a;
}

int main { }
{

myclass obi, ob2;


obl.set_a(10) ;
ob2.set_a(99) ;
cout o b l . g e t _ a ( ) " \ n " ;
cout ob2.get_a() " \ n " ;
return 0;
}

, 10 99.
2. myclass . , myclass. (
get_a().) , ,
. , , myclass , , mainQ
:
//
#include <iostream>
using namespace std;
int main()

{
myclass obi, ob2;
obi. a = 10;
2. =99;

// !
//

cout obl.get_a() "\n";


cout ob2.get_a() "\n";
return 0;
3. , -,
-. ,
myclass, , , :

30

C++

^include <iostream>
using namespace std;
class myclass {
public:
//
int a;
// set__a() get_a()

int main{)
{

myclass obi, 2;
//
. = 10;
2. = 99;
cout . "\";
cout 2. "\";
return 0;

, myclass,
main(). , (.)
. , -,
- ,
, (.),
. ,
.
4. ,
. stack,
, :
#include <iostream>
using namespace std;
^define SIZE 10
// stack
class stack {
char stck[SIZE]; //
int tos; //
public :
void init(); //
void push(char ch) ; //
char pop (); //

1, C++
II
void stack::init()
tos=0;

\
I/
void stack::push(char ch}
if (tos=SIZE) {
cout " ";
return;
J
stckftos] = ch;
tOS++;

'
//
char stack::pop()
if (tos==Q) {
cout " ";
return 0; //
}
tos;
return stck[tos];
int main(}
stack si, s2; //
int i;
//
si.init ();
s2.init () ;
si.push ('a');
s2.push f'x'};
si.push('b');
s2.push('y1);
si.push ('c');
s2.push ('z1);
for(i=0;i<3;i++) cout " si:" sl.popO "\n";
for(i=0;i<3; i++) cout " s2:" s2.pop() "\n";
return 0;

31_

C++

32

si
si
si
2:
s2:
s2:

. stack
: stck tos. stck , , a tos .
init(), pushQ (), , ,
, .
lain() , si s2, . , () . si
s2. stck tos. .
-,
.

1. , ,
.
2. card, .
,
. , . - store() - show() .
main() .
3. . 100
. main() .

1.6. C++
C++ . ,
C++. ,
.
-, , void . , -

1. C++

33_

fl() ( char), :
char f I ( v o i d ) ;

C++ void . C++ :


char f1() ;
C++ .
, ,
. C++ ,
. void . ( void , , .
C++
, void .) , C++
:
int f l ( ) ;
int f 1 ( v o i d ) ;

C++ , C++ . ,
, ,
C++ . , - , ,
.
Q C++ , C++
void ,
return .
void
-. ,
.
, ,
. C++
. , .
C++ ,
C++ .
, "". C++

34

C++

.
,
.
. ( )
C++ boot. C++
true false , boot. C++
bool,
bool.
, .
: ,
, . C++ , true,
false. : true 1, a false 0,
bool . C++
bool
. ,
, .

1. , ,
main() :
int

main(void)

C++ void .
2. C++ , sum() :
//
^include <iostream>
using namespace std;
int

main()

(
int a,b,c;
cout " : ";

cin a b;
c=sum(a, b);
cout " :" ;

1.

C++

35

return 0;
//
sum{int a, int b)
{
return a+b;

3. ,
:
ttinclude <iostrearn>
using namespace std;
int main ( )
{
int i; // ,

cout " :";


cin i;
//
int j, fact=l; // ,
//
for (j=i; j>=l; j ) fact=fact * j ;
cout " :" fact;
return 0;

j fact ,
.
4. outcome false. if.
^include <iostream>
using namespace std;
int m a i n ( )
bool outcome;
outcome = false;
if(outcome) cout "";
else cout "";

36

C++

return 0;

,
.

1.
C++. ?
//
#include <iostream>
using namespace std;
int

main()

ft);
return 0;

)i

void f ()
cout " ";
2. C++. ,
, .

1.7.
, ,
C++ (function overloading). , C++ , , C+ + .

,
.
C++ ,
, , .
;::.! ,; . , .

7.

C++

37

, .
: . / .

C++ .
, C++.

, , . ,
, , .
.
, abs(),
labs() fabs(), , ,
, . - ,
,
, . , . ,
C++,
, :
#include <iostream>
using namespace std;
// a b s ( )
int abs(int n ) ;
long abs(long n ) ;
double abs(double n ) ;
int

main()
cout " -10:" abs (-10) " \ n / n " ;
cout " -10L:" abs (-10L) " \ n / n " ;
cout " -10.01:" abs (-10. 01) "\n/n";
return 0;

38

C++

II abs {)
int abs (int n)
{
cout " abs()\n";
return n<0 ? -n: n;
}
// abs()
long abs (long n)
{
cout " abs()\n";
return n<0 ? -n: n;
}
// abs()
double abs (double n}
{
cout " abs() \n";
return n<0 ? -n: n;

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


abs(), .
:
abs ( )
-10:
abs ( )
-10L:

10
10

abs()
-10.01: 10.01

,
. , , , abs(), labsQ fabs(), .
, .
( ).
.
, ,
.
,
, , ,
" , " .

1. C++

39_

2. .
date() ,
.
.
ttinclude <iostream>
using namespace std;
void date(char *date); //
void date(int month, int day, int y e a r ) ; //
int main{)
{
date("8/23/99");
date( 8, 23, 9 9 ) ;
return 0;
//
void date (char *date)
{
cout ":" date "\n";
}
//
void date (int month, int day, int year)
{
cout ":" month "/";
cout day "/" year "\n";

,
.
, ,
, , .
3. , . , :
ttinclude <iostream>
using namespace std;
void f l ( i n t a ) ;
void fl(int a, int b);
int main{)

fl(10, 2 0 ) ;

40

return 0;
}

void f l ( i n t a)
cout "B f l ( i n t a) \n";
void f l f i n t a,

int b)

cout "B f l ( i n t a, int b) \n'

4. , . ,
. , ,
:
//
int fl{int a);
double fl{int );

f1 (10); // ???

, ,
fl{) .

1. sroot(),
. sroot() :
, . ( sqrt().)
2. C++ :
double atof (const char s) ;
int atoi (const char *s)
long atol(const char *s)

, ,
s. , atof() double, atoi
int atoi long. ?
3. min(), , .

1, C++

41

min() , ,
.
4. sleepQ,
, . sleep()
, , ,
. ,
10 :
sleep (10);
sleepf'lO") ;

, . (
.)

1.8. C++
C++ 30 , C++.
C++ . 1.1.
C++ overload,
.
1.1. C++

asm

const_cast

explicit

int

register

switch

union

auto

continue

extern

long

reinterpret_cast

template

unsigned

bool

default

false

mutable

return

this

using

short

throw

virtual

signed

true

void

break

delete

float

namespace

case

do

tor-

new

catch

double

friend

operator

sizeof

try

volatile

char

dynamic_cast

goto

private

static

typedef

wchar_t

class

else

if

protected

static_cast

typeid

while

const

enum

inline

public

struct

typename



.
1. , .
2. C++ ?

42

C++

3. , / C++, . (, 2 4,
24, 16.)
4. rev_str()
. rev_str() , . , .
, . :
char sl[80], s2[80];
s t r c p y f s l , "") ;
rev_str(sl, s2}; // s2,
// si
rev_str{sl);
// si

5. ,
C++. ,
.
^include <iostream>
using namespace std;

int f (int a} ;

int main{)
{
cout f (10) ;
return 0;

}
int f(int a)
{
return a * 3.1416;

6. bool?

.
C++, .


,
.
1. , / C++
.
2. , . .
.
,
. ( store() display().)
3. rotate(),
. ,
(mt) (long). (
, ,
.)
4. ?
^include <iostream>
using namespace std;
class myclass {
int i;
public:

44

C++
int main ()

{
myclass ob;
ob.i = 10;

2.1.
, , . .
, , , ,
- . C++ -
(constructor function), . . ,
.
, , ,
. ,
:
ttinclude <iostream>
using namespace std;
class myclass {
int a ;
public:
myclass (); //
void show() ;

myclass : :myclass ( )
{
cout " \";
a-10;
)
void myclass :: show ()
{
cout a;

2.

45

int main ( )
{
myclass ob;
ob. s h o w ) ) ;
return 0;


myclass(). , ob. ,
, . , C++
" ".
. C++, ,
.
, myclassQ. , . C++
.
, . .
, , (destructor).
.
. , , .
, ~ () . :
^include <iostream>
using namespace std;
class myclass (
int a;
public:
myclass (); //

-myclass (); //
void show() ;

,.
'
myclass : :myclass ( )
{
cout " \";
a = 10;

46

C++

myclass::~myclass ()
{
cout ". . ";
}

void myclass::show()
{
cout a "\n";
}
int main()
myclass ob;
ob.show ();
return 0;

.
, . .
.

, . ,
,
. ,
pi 100 . ,
, .

1. , 1 stack
.
, . stack, :
^include <iostream>
using namespace std;
^define SIZE 10

2.
// stack
class stack {
char stck[SIZE]; //
int tos; //
public:
stack(); //
void push(char ch); //
char pop(); //
//
stack: : stack ()
{
cout " \";
tos=0;
//
void stack: : push (char ch)

<

if {tos==SIZE} {
cout " ";
return;
}
stck[tos]=ch;
tos++;

//
char stack::pop()
{
if (tos==0) {
cout " ";
return 0; //
}

tos ;
return stck[tos];
}

int main ( )
(
//
stack si, s2;
int i ;
si. push ( 'a' ) ;
s2.push( 'x' ) ;
sl.push('b') ;

47

48

C++
s2. push ') ;
si.push('');
s2.push('z');
for(i=0; i<3; .i++) cout " si:" sl.popO "\n";
for(i=0; i<3; i++} cout " s2:" s2.pop() "\n";
return 0;

, ,
. . ,
, . , , .
2. ,
. , . strtype,
,
. strtype , .
ftinclude <iostream>
^include <cstring>
^include <cstdlib>
using namespace std;
^define SIZE 255
class strtype {
char *p;
int len;
public:
s t r t y p e ( ) ; //
- s t r t y p e ( } ; //
void set(char *ptr);
void s h o w ( ) ;

//
strtype::strtype()
p=(char *) m a l l o c ( S I Z E ) ;
if(!p) {
cout " \";
exit ( 1 ) ;

2.

__

__

49

*='\0';
1=0;
//
strtype: :~strtype ()
cout " \";
free () ;

}
void strtype: : set (char *ptr}
{
if (atrlen(p) > =SIZE) {
cout " ";
return;
1
strcpy(p, ptr) ;
len=strlen{p) ;
1
void strtype: : show ()
{
cout p " : " len;

cout "\n";
1
int main ()
(
strtype sl,s2;
sl.set("3TO ");
s2. set (" C++");
si. show ( ) ;
s2. show() ;
return 0;


maUoc() free(). ,
, C++ .

V

.
1, -

50

__

________

__

C++

, .
,
.

3. . timer .

. . ,
.
^include <iostream>
#include <ctime>
using namespace std;
class timer (

clock_t start;
public:
timer ( } ; //
~timer ( ) ; //

>;
timer: : timer ()
{
start=clock() ;
timer: : -timer ()
j
clock_t end;

end=clock() ;
cout " :" (end-start) /CLOCKS_PER_SEC <<"\n";
}

int main()
(
timer ob;
char c;
// . . .
cout " , ENTER: ";
cin ;
return 0;

clock(),
. CLOCKS_PER_SEC, .

2.

51

1. queue (. . 1) , .
2. stopwatch . 0. -
start() stop() . - show() . ,
stopwatch, . ( .)
3. , ?
class sample {
double a, b, ;
public:
double sample!); // , ?

2.2.
. .
. , , :
^include <iostream>
using namespace std;
class myclass {
int a;
public:
myclass{int x); //
void show() ;
myclass::myclass(int x)
{
cout " \";
a = x;
\

void myclass::show()
{
cout a " \ n " ;

52

C++

int main()

myclass ob(4);
ob. show()-;
return 0;

myclass . , myclass(), . , main() ob.


4, , ,
mycIassQ, .
, :
myclass ob = myclass(4);

C++
. ,
,
(copy constructor), . .

,
.
:
.

1. .
myclass() :
#include <iostream>
using namespace std;
class myclass {
int a, b;
public:
myclass(int x, int y); //
void show (};

2. ^
m y c l a s s : i m y c l a s s ( i n t ,

53
int )

cout " \";


= ;

- ;
-/oid myclass: :show()
cout a ' ' b "\n";

int main ( }
myclass o b ( 4 , 7) ;
ob. show() ;
return 0;

4 , 7 . (,
, ).
2. stack,
"". .
^include <iostream>
using namespace std;
^define SIZE 10
// stack
class stack {
char s t c k [ S I Z E ] ; //
int tos; //
char who; //
public:
stack(char ) ; //
void push(char ch) ; //
char pop ( } ; //
//
stack: :stack(char )

tos = 0;
who = ;

54

C++

cout " " who "\";

)
//
void stack: :push(char ch)
{
if (tos==SIZE) {
cout " " who " \n";
return;
}
stck [tos]=ch;
tos--;
!
//
char stack: :pop()
{
if (tos==0) {
cout " " who " ";
return 0; //

tos ;
return stck[tos];
int main{)
//
stack si ('A') , s2('B') ;
int i;
si. push ( 'a' ) ;
s2.push('x') ;
sl.push('b') ;
s2.push('y') ;
si. push ( 'c' ) ;
s2 . push ( ' z ' ) ;
//
for(i=0; i<5; i++) cout " si: "
si. pop {) "\n";
for(i=0; i<5; i+-t-) cout " s2 : "
s2.pop() "\n";

return 0;
"" , ,
, ,
.

2.

55_

3. strtype,
:
^include <iostream>
#include <cstring>
^include <cstdlib>
using namespace std;
class strtype {
char *p;
int len;
public:
strtype(char *ptr);
-strtype ( } ;
void show() ;
strtype::strtype(char *ptr)
len = strlenfptr);

p = (char *) malloc(len + 1 ) ;
cout " \";
exit (1) ;
strcpy(p, p t r ) ;
strtype: : -strtype ()
cout " \";
free(p);
void strtype::show()
cout p "- : " len;
cout "\n";

>
int main()
strtype si(" "), 2(" C++");
si.show();
s2. show () ;
return 0;
strtype .

56

C++

4. , . ,
:
#include <iostream>
using namespace std;
class myclass {
int i, j;
public:

myclass (int a, int b) ;


void show() ;

};
myclass: :myclass (int a, int b)
!
i = a;
j = b;

"
void myclass: : show ( )
{
cout i ' ' j "\n";
}

int main { )
{
int x, y;
cout " : ";
cin x ;
// ob
myclass ob(x, ) ;
ob.showf) ;
return 0;

. , . C++, ,
" ".

]
1. stack , .
. ( .)

2,

57

2. t_and__d, .
-, .
(:
.)
3. box,
double, . box

double. - vol(),
box.

2.3.
(inheritance) 7, .
C++ ,
.
, .
,
. , , , (base class).
(derived class). .
, . , .
, .
, ,
, , ,
.
:
//
class {
int i;
public:
void set_i(int n) ;
int g e t _ i ( ) ;
};

, :
//
Class D: public {
int j;

58

__

C++

public:

void set_j (int n) ;


int raul () ;
. ,
D ,
public . , D . public , , ,
,
.
.
,
D:
//
^include <iostream>
using namespace std;
//
class {
int i;
public:
void set_i(int n) ;
int get_i ( ) ;

//
class D: public {
int j;

public:
void set_j {int n) ;
int mul ( ) ;

// i
void B::set_i(int n}
{
i = n;
}

// i
int : :get_i ()
<

return i;

2.

59

// j
void D: :set_j (int n)
t

j = n;

// i j
int D: :mul (}
//
// -
return j * get_i(};
}

int main ( )
{
D ob;
ob.set_i (10) ; // i
ob.set_j(4); // j
cout ob.mul(); // 40
return 0;
1

mul(). ,
get_i()j , D,
D . , D. mu1() i,
get_i(),
( i)
. ,
. ,
.
:
class ; _ {

_ ( )
: public (), private () protected ().

60

+_+_

public. .

|
^____

1. , fruit,
.
Apple Orange. ( ).
//
^include <iostream>
ttinclude <cstring>
using namespace std;
enum yn (no, yes};
enum color {red, yellow, green, orange};
void out (enum yn x) ;
char *c[ ] = {
"red", "yellow", "green", "orange"};
//
class fruit {
//
public:
enum yn annual;
enum yn perennial;
enum yn tree;
enum yn tropical;
enum color clr;
char name [40] ;
>;
//
class Apple: public fruit {
enurn yn cooking;
enum yn crunchy;
enum yn eating;
public:
void seta (char *n, enum color c, enum yn ck, enum yn crchy,
enum yn e) ;
void showf) ;
//
class Orange: public fruit (
enum yn juice;

2,

67

enum yn sour;
enum yn eating;
public:
void seto(char *n, enum color c, enum yn j, enum yn sr, enum yn e) ;
void show ( ) ;

void Apple: : seta (char *n, enum color c, enum yn ck, enum yn crchy,
enum yn e)
{
strcpy (name, n) ;
annual = no;
perennial = yes;
tree = yes;
tropical = no;
clr = c;
cooking = ck;
crunchy = crchy;
eating = e;

void Orange: :seto (char *n, enum color c, enum yn j, enum yn sr,
enum yn e)
{
strcpy (name, n} ;
annual = no;
perennial = yes;
tree = yes;
tropical = yes;
clr = c;
juice = j;
sour = sr;
eating = e;

void Apple: :show()

{
cout
cout
cout
cout
cout
cout
cout
cout
cout
cout

name " : " "\n";


" : "; out{annual};
" : "; out (perennial) ;
": "; out(tree);
": "; out (tropical) ;
": " c[clr] "\n";
" : "; out (cooking) ;
" : "; out (crunchy) ;
": "; out (eating);
"\n" ;

62

C++

void Orange : : show { )


{
cout name " : " "\n";
cout " : "; out (annual);
cout " : "; out (perennial) ;
cout ": "; out (tree);
cout
cout
cout
cout
cout
cout

": "; out (tropical) ;


": " c[clr] "\n";
" : "; out(juice);
": "; out (sour) ;
": "; out (eating);
"\n";

void out{enum yn x)
{
if (x==no) cout "\";
else cout "\";
int main()
{
Apple al, a2;

Orange ol, o2;


al . seta (" ", red, no, yes, yes);
a2. seta ("", red, yes, no, yes) ;
ol. setoC'nyn", orange, no, no, yes);
o2.seto ("", orange, yes, yes, no);
al .show( ) ;
a2 . show ( ) ;
01 .show{ ) ;
02 . show ( ) ;

return 0;
, fruit , , (,
, fruit .)
, .
,
. . Apple Orange.
, .
.
, .

2.

63_

, .
: "" . .

)
^

~^^

1. :
class area_cl {
public:
double height;
double width;

rectangle isosceles, _1. (),


(rectangle)
(isosceles).
height width ( , ) .

2.4.

(.). , .
.
(->). (
(->) .)
, . ,
.
&, ,
.
,
, .

1. :
#include <iostream>
using namespace std;

64

C++
class myclass {
int a;
public:
myclass (int x} ; //
int get ( } ;

myclass: :myclass (int x)

int myclass: : get ()


f
return a;

int main()
,
myclass ob(120); //
myclass *p; //
= sob; // ob
cout ", :" ob.getO;
cout "\n";
cout ", : " p->get ( } ;
return 0 ;

.
,
myclass *p;

myclass. : ,
.
ob , :
= sob;

, ,
.
4,
C++.

2.

65

2.5. ,
, . , , ,
. C++ , , , -,
. , , , , , .
:
struct {
// .
private:
//
}

, C++ , . . private,
, .
, , . , C++,
.
, class .
"" "" .
"" , .
C++. ,
C++. ,
,
,
. , , C++, .
"" - C++
, -.
,
-. , ,
class.
. (

66

C++

struct ,
-.)
, C++:
! C++
,
. ,
, private.
, C++ , , ( , ). . C++
.
,
, , .
- .

, . , .
C++ ,
. -,

. .
,
.
C++ --
(anonymous union). .
, .
. ,
, (.). , :
union { //
int i;

char c h [ 4 ] ;
};
// i ch
i = 10;
ch[0] = 'X';

, , i ch
, . .

2.

67

,

.
,
.
,
, .
.
. .
.

1. , struct:
# include <iostream>
^include <cstring>
using namespace std;
//
struct st_type {
st_type (double b, char *n) ;
void show{) ;
private:
double balance;
char name [40] ;
st_type: : st_type (double b, char *n)
{
balance = b;
strcpy (name, n) ;
}
void st_type: :show{)
{

cout ":" name;


cout ":$" balance;
if (balance < 0.0) cout "***";
cout "\n";

}
int main(}
{
st_type
st type

accl(100.12, "Johnson") ;
acc2(-12.34, "Hedricks" )

68

C++

accl.show() ;
acc2.show{) ;
return 0;

, , ,
.
private.

C++. C++ ,
. ,
,
struct.
, :
^include <iostream>
ttinclude <cstring>
using namespace std;
class cl_type (
double balance;
char name[40];
public:
cl_type{double b, char *n);
void show();
cl_type: :cl_type {double b, char *n)
(
balance = b;
strcpyfname, n) ;
}
void cl_type : : show( )
(
cout ":" name;
cout ":$" balance;
if (balance < 0 . 0 ) cout "***";
cout "\n";
}

int
{

rnainf)
cl_type
cl_type
accl ,show() ;
acc2.show() ;

accl(100.12, "Johnson");
acc2(-12.34, "Hedricks")

2.

69

return 0;

2.
double :
^include <iostream>
using namespace std;
union bits (
bits (double n) ;
void show_bits ( ) ;
double d;
unsigned char c[sizeof (double)];

1;
bits: :bits (double n)
{
d = n;

void bits : : show_bits { )


{
int i, j;
for( j = sizeof (double) 1; j >= 0; j ) {
cout " " j
for( i = 128; i; i = 1)
if(i & c[ j ]) cout "1";
else cout "0";
cout "\n";

int main{ )
{
bits .991.829) ;
ob.show_bits () ;
return 0;

7: 01000000
6: 10011111
5: 00011111
4: 01010000
3: 11100101

70

C++

2: 01100000
1: 01000001
0: 10001001
3. . strtype .
.
# include <iostrearn>
# include <cstring>
^include <cstdlib>
using namespace std;

struct strtype {
strtype (char *ptr) ;
~strtype (} ;
void show() ;
private :
char *p;
int len;
<! #

strtype: :strtype (char *ptr)


{
len = strlen(ptr);
p = (char *) m a l l o c f l e n + 1) ;

if<!p> {
cout " \";
exit(l) ;
strcpy{p, ptr) ;

strtype: : -strtype ()
(
cout " \";
free (p) ;
1
void strtype: : show {}
(
cout p "- : " len;
cout "\n";
int main ()
strtype si(" "}, 2(" C++");

2.

-71

Sl.showl);
s2 . show {) ;
return 0;

4.
double . (,
double .)
//
^include <iostream>
using namespace std;
int main(}
union {
unsigned char bytes[8];
double value;
);
int i;
value = 8 5 9 3 4 5 . 3 2 4 ;

// double
f o r ( i = 0 ; i<8; i++)
cout (int) b y t e s [ i j " ";
return 0;

, value bytes
, , . ,
, ,
.
, .

1. stack, 2.1,
.
2. ,
( 16- ; 32- , short int).
3. , .

72

C++

2.6.
. C++ , , .
, .
(in-line) , . ,
.
(, ,
,
. ,
.)
,
, . - .
inline
. , , :
//
^include <iostreara>
using namespace std;

inline int even (int x)


{
return ! (x%2);
int main ()
{
if (even (10)) cout "10 \";
if (even (11)) cout "11 \";
return 0;

even(),
, . ,
if (even(10)) cout "10 \";

if (! ( 1 0 % 2 ) ) cout "10 ";


: .

2.

73

, ,
.
even() main().

. -,
. , ,
. .
-, ,
. , C++ .
, inline
, . , , , ,
, inline .
. , ,
(static) , ,
switch, goto.
, .

- , .

, . , divisible!)
. ( , .)
// -
^include <iostream>
using namespace std;

74

C++

class samp {
int i , j ;
public:
sampfint a, int b) ;
int divisible ; //
samp: : samp {int a, int b)
(
i = a;
j .= b;
/* 1, i j.
*/
inline int samp: :divisible ()
{
return ! (i%j ) ;

int rnainO
ii
samp obi[10, 2), ob2(10, 3);

//
if(obi.divisible{)) cout "10 2";
//
if(ob2.divisible()} cout "10 3\";
return 0;

2. . ,
min() . .
tfinclude <iostream>
using namespace std;
// min ( )
// int

inline int min {int a, int b)


{
return a < b ? a: b;
// long
inline long min (long a, long b)

2.

75

return < b ? : ;
}

// double
inline double rain (double a, double b)
{

return a < b ? a: b;

int main ( )
{

cout min(-10, 10) "\n";


cout min(-10.01, 100.002) "\n
cout min(-10L, 12L) "\n";
return 0;

1. 1 abs() , int, long double. ,


.
2. ?
void f l ( )
{
int i;

f o r d = 0; i < 10; i++) cout i;

2.7.

- , . , ,
, .
, inline . ( .) ,
, divisible()
:

76

__

__

#include <iostream>
using namespace std;
class samp {
int i, j;
public:
samp (int a, int b) ;
/* divisible (), ,
.
V
int divisible () { return !(i%j); }
samp: : samp (int a, int b)
{
i = a;
j = b;
}
int main ()
{
samp obi (10, 2), ob2(10, 3);
//
if (obi .divisible () ) cout "10 2\";
//
if (ob2. divisible () ) cout "10 3\";
return 0;

, divisibleQ
samp. , divisible{)
, . divisible()
samp .
, , ( ), , ,
.
, divisibleQ samp, . . C++ ,
. . samp :
class samp {
int i, j;

2.
public:
samp(int a,

77

int b);

/* divisible(), ,
.
*/
int divisible()

'

return ! ( i % j ) ;

divisibleQ . , . C++
.
, .

1.

,
, . , samp :
ttinclude <iostream>
using namespace std;
class samp {

int i, j ;
public:
//
samptint a, int b) { i = a; j = b; }
int divisible() { return ! { i % j ) ; }

samp() samp ,
.
2. ,
.
:
class myclass {
int i;

78

C++
public:
myclass(int n) ( i = n; }
void show(} { cout i; }
it

show() . ,
, , , /,
/, , .
C++, ,
. ,
.

1. stack 2.1, 1, , ,
, .
2. strtype 2.2, 3, , .


.
1. ? ? ?
2. line, .
len. line
.
. , , *. :
line.
3. ?
^include <iostream>
using namespace std;
int
{

main()
int i = 10;

long 1 = 1000000;
double d = -0.0009;

2.
cout i ' ' 1 ' ' d;
cout " \ n " ;
return 0;
I

4. , _!
2.3, 1. cylinder
. : 2 * pi * R2 +
pi * D * .
5. ? ?
6. , -
:
#include <iostream>
using namespace std;
class myclass {
int i, j;
public:
myclass (int x, int y) ;
void show() ;
};
myclass: :myclass (int x, int y)
f

i = x;
j = Y;
}

void myclass :: show (}


{

cout i "" "" j "\n";


}

int main()
{
myclass count (2, 3);

count . show ( ) ;
return 0;
}

7. ?
8. ?
union {
float f;

unsigned int bits;


1;

C++



, .
1. prompt. - . -
.
' count. prompt
, , count.
2. 1 . .
.
.
3. dice, .
11(), randQ, 1 6. roll()
.

. , , , .
: (friend) .


,
.
1. , ?
class widgit {
int x, ;
public:
// ...

};

2. ? ?
3. , , Mars.
class planet {
int moons;
double dist_from_sun;
double diameter;
double mass;
public:
// ...
1;

4. . ?
5. , , .

82

C++

6. , , ob,
100 , X .
class sample {
int a;

char ;
public:
sample(int x, char ch) { a - x; = ch; }

3.1.
, .
, , - . ,
ol 2, ol
2. :
//
#include <iostream>
using namespace std;
class myclass {
int a, b;
public:

void set (int i, int j) { a ~ i; b = j; }


void show{) { cout a ' ' b "\n"; }
int main ( )
<
myclass ol, o2;
ol.set(10, 4);
// ol 2
o2 = ol;
ol.show( ) ;
o2 . show ( ) ;
return 0;

b ol 10 4. ol 2. -

3.

83_

, ol.a 2., ol.b o2.b. ,


:
10 4
10 4

,
. - . , ol.setQ ol.a 2,
.

, . , . ,
,
. , :
//
#include <iostream>
using namespace std;
class myclass f
int a, b;

public:
void set(int i , int j ) { a = i ; b = j ; }
void show() { cout a ' ' b "\n"; }
/* myclass, -
.
*/

class yourclass I
int a, b;
public:
void set(int i, int j) { a = i; b = j; }
void show() { cout a ' ' b "\n"; }
};

int main()
rayclass ol;
yourclass o2;
ol.set(10, 4);

_84

C++
2 = ol; // ,
ol.show();
2 . show () ;
return 0;
}

myclass yourclass ,
, .
2. , -
- .
, . ,
stack
si, stck s2 a, b .
ttinclude <iostream>
using namespace std;
#define SIZE 10

// stack
class stack {
char s t c k [ S I Z E ] ; //
int tos; //
public:

s t a c k ( ) ; / /
void push(char ch); //

char p o p ( ) ; //
};
//
stack::stack()
(
cout " \";

tos = 0;

//
void stack::push(char ch)
{
if

(tos==SIZE) {
cout " \";
return;

)
stck[tos] = ch;
tos+-(-;

3.

//
char stack: :pop()
{
if (tos==0) {
cout " \";
return 0; //

tos ;
return s t c k f t o s ] ;
int main ()
II ,
stack si, s2;
int i ;
si. push ( 'a' ) ;
si. push ( 'b* ) ;
si .push( 'c' ) ;
/ / si s 2
s2 = si; // s2 si
for(i=0; i<3; i++J cout " si:" sl.popi)
"\n";
for(i=0; i<3; i++) cout " s2:" s2.pop()
"\n";
return 0;

3. . , strtype, 2. .
//
^include <iostream>
#include <cstring>
^include <cstdlib>
using namespace std;
class strtype {
char *p;
int len;

public:
\
strtype(char *ptr);
~strtype() ;
void s h o w f ) ;

86

__

C++

strtype: :strtype (char *ptr)


(
len=strlen(ptr) ;
p=(char *} malloc (len+1) ;
if(!p) (
cout " \";
exit(l) ;
}
strcpy {p, ptr) ;
strtype: :~strtype (}
{
cout " \";
free (p) ;
}
void strtype: : show ()
{

cout p " : " len;


cout "\n";
}
int main ()

f
strtype !(" "), 2(" C++")
si. show () ;
s2. show () ;
// si s2
s2 - si;
s 1 . show { ) ;
s2 . show ( ) ;
return 0;

. si s2,
. .
strtype , . si s2, s2
, si. ,
, ,
si, , ,
s2, .
,
.
,

3.

87

, ,
.

1 . ?
//
^include <iostream>
using namespace std;
class ell {
int i, j ;
public:
ell (int a, int b)

{ i = a; j = b;

class c!2 (
int i, j;
public:
c!2(int a, int b) { i = a; j = b; }

int main ( }
{
Cll x(10, 20} ;
c!2 y(0, 0);
x = y;

2. queue, 2, 2.1,
1, , , , .
3. queue ,
?

3.2.
,
. ,
, -

88

C++

. ,
.

1. :
#include <iostream>
using namespace std;
class samp {
int i;
public:
samp(int n) { i = n; }
int get_i{) ( return i; ).
// o.i.
int sqr_it(samp o)
return o.get_i{) * o.get__i(};
int mainf)
{

samp a(10) , b(2) ;


cout sqr_it(a) "\n" ;
cout sqr_it(b) "\n";
return 0;
samp, i. sqr_it() samp,
i .
100 4.
2. C++, ,
. , , , .
. :
/* , , ,
.
, ,
.

3.

89

#include <iostream>
using namespace std;
class samp {
int i;
public:
samp(int n) { i = n; }
void set_i(int n) { i = n; }
int get_i() { return i; }
\.
/* o.i .
, sqr_it {}
*/
void sqr_it(samp )
{
o.set_i( o.get_i() * o.get_i());
cout " i : " o.get_i{);
cout. "\n";
int main()
samp a (10);
sqr_it(a); //
cout " a.i mainf) : ";
cout a.get i(); // 10
return 0;

:
i : 100
a . i m a i n ( ) : 10

3. ,
, .
, . ,
,
sqr_it(), .
/* sqr i t ( )
, .
V

^include <iostream>
using namespace std;

90

__

C++

class samp {
int i ;
public :
samp (int n) { i = n; }
void set_i(int n) { i = n; }
int get_i() ( return i; }

/* o.i . ,

*/
void sqr_it (samp *o)
{
o->set_i {o->get_i ( ) * o->get_i ( ) ) ;
cout " i : " o->get_i();
cout "\n";

int main()
{
samp a (10) ;
sqr_it (fia) ; // sqr_it ( }
cout " main() :";
cout . get_i ( ) ; // 100
return 0;
}

:
i : 100
m a i n ( } : 100
4. , ,
. , , , . . , , ? , , ?
.
, . . ,
. , ,
, .

3.

91

,
. , . ,
, , , .
, ,
, . ,
( ), .
:
^include <iostreara>
using namespace std;
class samp {
int i ;

public:
samp(int n) (
i = n;

cout " \n";


}

-samp ( ) { cout " \n"; )


int get_i() { return i; }

1;
// o.i
int sqr it(samp o)
return o.get_i() * o.get_i();
int main ()
{

samp a (10);
cout sqr__it(a) "\n";
return 0;
}

:

100



, . . .

92

C++

, ,
sqr_it(), .
, , , ,
. , , , , ,
. . ( . 2 .) , , , , , -
.
, , ,
,
. ,
. ( , C++ , .) ,
, , ,
(copy constructor). . ( 5.)

1. stack 3.1, 2, showstack(), stack.


.
2. , , . , , . , ,
?
// v-PrPa:Mbie
#include <iostream>
#include <cstdlib>
using namespace std;
class dyna j
int *p;
public:
dyna f i n t i ) ;
~dyna() ( f r e e ( p ) ; cout " \"; }

3.
int get () { return *p; }

dyna : : dyna { int i )


{
p = (int *) malloc {sizeof (int) ) ;
if(!p) {
cout " \";
exit(l) ;

// *ob.p
int neg(dyna ob}
return -ob.getf);

1
int main()
{
dyna (-10) ;
cout o . g e t f } " \ n " ;
cout n e g ( o ) "\n";
dyna o2{20) ;

cout o2.get() "\n";


cout neg{o2) "\n";
cout o.get() "\n";
cout neg(o) "\n";
return 0;

3.3.

,
. , -,
, .
-,
return.

94

C++

: ,
.
, . ,
2 .

1. :
//
^include <iostream>
^include <cstring>
using namespace std;
class samp {
char s[BO];
public:
void show() { cout s "\n"; }
void set(char *str) { strcpyts, str); }
// samp
samp input(}
{
char s[80];
samp str;
cout " : ";
cin s;
str.set (s);
return str;
int main()
{
samp ob;
// ob
ob = input();
ob.show();
return 0;

3.

95

input() str
. str.s, str. main() input() .
2. ,
,
, . , , , ,
, , , . ,
:
//
#include <iostream>
#include <cstring>
^include <cstdlib>
using namespace std;
class samp {
char *s;
public :
samp ( ) { s = ' \ 0 ' ; }
~samp() { i f ( s ) f r e e ( s ) ;
cout " sNn"; }
void show () { cout s "Nn"; }
void set (char *str) ;
//
void samp: : set (char *str)
s = (char *} malloc (strlen(str) +1) ;
if(!s) {
cout "
exit(l) ;
strcpy (s, str) ;
}
// samp
samp input ()
(
char s[80] ;
samp str;
cout " : ";
cin s;

36

C++

s t r . set ( s ) ;

return str;

int mainf)

{
samp ob;
/ / ob
ob = input (); //
ob. show () ;
return 0;

:
:
s
s

s
Null pointer assignment

, samp .
, str input() . ~samp()
, , input().
, , ( ) ,
. str,
. ,
,
. , ob ().
,
, input()
, . ,
samp
,
,
, "Null pointer assignment". (
,
.)
, ,
, , , -

3.

97

. ( 5,
.)

,
, who.
who ,
. :
who #x

, . :
who #x

. ,
make_who(), who.
.
.
2. , , , .

3.4. :
, , . C++ (friend
functions). ,
.
, /.
. . - ,
. , .
, , , . ,
, ,
friend. ,
, :

gg

__

C++

H
#include <iostream>
using namespace std;
class myclass (
int n, d;
public:
myclass (int i, int j) { n = i; d = j; }
// myclass
friend int isfactor (myclass ob) ;
};
/* .
, n d. ,
friend isf actor ()
.
*/
int isfactor (myclass ob)
{
if(!(ob.n % ob.d)) return 1;
else return 0;
}
int main{)
myclass obi (10, 2), ob2(13, 3);
if (isfactor (obi) cout "10 2\";
else cout "10 2\";
if (isfactor (ob2) cout "13 3\";
else cout "13 3\";
return 0;

myclass
isfactorQ. isfactor() myclass, isfactorQ
. isfactor() ob.n ob.d.
, ,
. ,
( ). ,
:
obi. is factor () ; // , isf actor () -

3.

99

,
.
"" , , . , -
myclass, d,
, .

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

, , . , , isfactorQ
ob myclass. isfactor() myclass,
ob. , isfactorQ
myclass,
ob.n, ob.d, d
myclass.


. ,
.

.
, .
, , , .

100

C++

1. ,
, . , , ( ) truck (),
:
^include <iostream>
using namespace std;
class truck; //
class car {
int passengers;
int speed;
public:
car(int p, int s) { passengers = p; speed = s; }
friend int sp_greater (car c, truck t) ;
class truck {
int weight;
int speed;
public:
truck(int w, int s) { weight = w; speed = s; }
friend int sp_greater (car c, truck t) ;
/* ,
. 0 .
, .
*/
int sp_greater (car c, truck t)
{
return . speed t. speed;
iI
int main()

int t;
car cl(6, 55), c2 (2, 120) ;
truck tl (10000, 55), t2(2000Q, 72);
cout " cl tl:\n";
t = sp_greater (cl, tl);
if(t<0) cout " . \";
else if (t==0) cout " . \";
else cout " . \";

3.

cout " 2 t 2 : \ n " ;


t - sp_greater(c2, t 2 ) ;

if(t<0) cout " . \n";


else if(t==Q) cout " . \";
else cout " . \";
return 0;
sp_greater(),
truck. ( , .) ,
truck, , , , truck ,
.
C++ (forward declaration),
(forward reference). sp_greater()
truck,
sp_greater() . . .
C++, ,
, :
class .;

, ,

class truck;

truck
sp_greater() .
2. . , ,
sp_greater() truck, :
ftinclude <iostream>
using namespace std;
class truck; //
class car {
int passengers;
int speed;

102

public:
car(int p, int s) { passengers = p; speed = s; }
int sp_greater(truck t);

class truck {
int weight;
int speed;
public:
truck(int w, int s) ( weight = w; speed = s; }
//
/ /
friend int car: :sp_greater (truck t);

/* ,
. 0 .
, .
*/
int car: :sp_greater (truck t)
{
/* sp_greater() car,
truck
*/
return speed t. speed;

int main ( }

int t;
car cl(6, 55), c2 (2, 120) ;
truck tl (10000, 55}, t2{20000, 72);
cout " cl tl:\n";
t = cl . sp_greater (tl) ; // - car
if(t<0) cout " . \";
else if(t==0) cout " . \";
else cout " . \n" ;
cout " 2 t2:\n";
t = c2 .sp_greater (t2) ; // - car
if(t<0) cout " . \";
else if{t==0) cout " . \";
else cout " . \n" ;
return 0;

3.


,
truck.
, sp_greater() .
, : , - -
-. .

( )
. -,
. ,
t = cl.sp_greater(tl);

() :
t = cl.car::sp_greater(tl);

cl , , sp_greater() , .

^ - *

1. , ! 2
,
, . inuse(), true,
false . prl, 2.
class prl {
int printing;
//...
public:
prl() { printing = 0; }
void set_print (int status) { printing = status; }

class pr2 {
int printing;

104

C++

public:

pr2 () { printing - 0; }
void set_print(int status) { printing = status; }

,
:
1.
?
2. :
class samp {

double *p;
public:
samp(double d) {
p = (double *) malloc(sizeof{double});
if(!p) exit(l); //
*p - d;
~samp() ( free(p); }

samp obi(123.09) , ob2(0.0);


// ...
ob2 = obi;

obi 2?
3. :
class planet {
int moons;
double dist_from_sun; //
double diameter;
double mass;
public:
//...
double get_miles() { return dist_from_sun; }

3.

105

Hght(),
planet , .
(, 186000
dist_from_sun, . . , .)
4. ?
5. stack, loadstack(), , (a-z). ,
. (. ,
.)
6. , .
7. ?



, .
1.
. loads tack() 5
,
upper. , upper 1,
.
.
2. strtype, 3.1, 3, , strtype . (
, ). get_string().
3.
, ,
? ,
.
class base {
int' a;

106
public:
void load_a(int n) { a = n; }
int get_a() { return a; }

class derived: public base {


int b;
public:
void load_b (int n) { b = n; }
int get b() { return b; }

C++


.
C++ .
C++, .

,
.
1.
?
2.
? ( .)
3. ,
. ? ?
4. , ,
, , . .
. ? ,
.
5. , make_sum(),
summation.
, ,
, . ,
.
class summation {
int num;
long sum; // , num

108

C++

public:
void setsum(int n);
void show_sum() (
cout " , " num
" " sum "\n";
};

void summation::set_sum{int n)
int i ;
num = n;
sum = 0;
for(1=1; i<=n; i++)
sum += i;

6. set_sum()
summation. , ?
7. , ,
isnegQ, myclass true,
num false .
class myclass {
int num;
public:
myclass(int x} { num = x; }
J;

8.
?

4.1.
, ,
, .
.
,
. ,

.

4. ,

109

!PWJ
>"

1. :
^include <iostream>
using namespace std;
class samp {
int a;

public:
void set_a(int n) ( a = n; }
int get_a{) { return a; }
int

mainO
samp ob[4] ;
int i;

for(i=0; i<4; i++) ob[ i ] . s e t _ a ( i ) ;


for(i=0; i<4; i++) cout ob[ i ] . g e t _ a ( ) ;
cout "\n" ;
return 0;

samp, 0 3. ,
- . ,
ob, ;
, - .
2. , . , ob :
//
^include <iostream>
using namespace std;
class samp {
int a;
public :
samp (int n) { a = n; }
int get_a() { return a; }
};
int main ( )
{
samp o b [ 4 ) = { -1, -2, -3,
int i;

-4 };

110

C++

for{i=0; i<4; 14+) cout ob [ i ].get_a() ' ';


cout "\n";
return 0;

1 2 3 4.
1 4 ob .

( 2):
samp ob[4] = { samp(-l) , samp (-2} , samp (-3) , samp (-4) } ;

, (, , , ).
3. . ,
:
//
^include <iostream>
using namespace std;
class samp {
int a;

public:
sampfint n) { a = n; }
int get_a() { return a; }
int mainO
samp ob[4] [2] = {
1, 2,
3, 4,
5, 6,
1, 8
};
int i;
for(i=0; i<4; i++) {
cout ob[i] [0],get__a() ' '
cout ob[i] [l].get_a() "\n
}
cout "\n";
return 0;

4. ,

111

:
12
3 4
5
7 8

4. , . .
:
^include <iostream>
using namespace std;
class samp (
int a, b;

public:
samp (int n, int rn) { a = n; b = m; }
int get_a() { return a; }
int get_b() { return b; }
int main ( )
I

samp ob [ 4 ] [ 2 ] = {

sampU, 2 ) , samp(3, 4 ) ,
sarnp(5, 6), samp(7, 8),
samp(9, 10), samp (11, 12),
samp(13, 1 4 ) , sarnp(15, 16)

1;
int i.;
for(i=0;
cout
cout
cout

cout

i<4
ob[i]
ob[i]
ob[i]

[0].get_a()

[0].get_b() "\n"
[l].get_a(J
ob[i] [ l ] . g e t _ b ( ) "\n"

J
cout "\n";
return 0;

samp . ob mainQ samp. , ++


-

112

++

. , ,
.
, ,
.

,
.
.
:
I 2
3 4
5 6
7 8
9 10
II 12
13 14
15 16

1. , 10
ch J. , .
^include <iostream>
using namespace std;
class letters {
char ch;
public:
letters (char c) { ch = c; }
char get_ch() { return ch; }

2. , 10 ,
num 1 10,
sqr num.
^include <iostream>
using namespace std;

4. ,

113

class squares {
int num, sqr;
public:
squares(int a, int b) { num = a; sqr = b; }

void show() {cout num ' ' sqr "\n"; }


3. ch 1 , (. . letters
).

4.2.

2,
. ,
(.),
(->).

: . , , . ,
.

- >

1. ;
//
#include <iostream>
using namespace std;
class samp (
int a, b;
public:
samp {int n, int m) { a = n; b = m; }
int get_a() { return a; }
int get_b() { return b; }

int main ( )
samp ob[4]
samp { 1 , 2 ) ,

114

C++
samp(3, 4),
samp(5, 6),
samp(7, 8)
int i;

samp *p;
p = ob; //
for(i=0;
cout
cout
P-H-;

i<4; i++) {
p->get_a(} ' ';
p->get_b() "\n";
//

cout "\n";
return 0;
:
1 2
3 4
5
7 8

,
.

1. 1 ,
ob .
2. 3 4.1 ,
. : C++, ,
, , .

4.3. this
C++ this. , - , . , :
ob.fl(); // , ob

4. ,

fl() ob. this.


, this -.
this .

1. , -
, . ,
,
inventory:
/ / this
#include <j_ostream>
^include <cstring>
using namespace std;
class inventory {
char item[20];
double cost;
int on_hand;
public:
inventory(char *i, double c, int o)
{
strcpy(item, i);
cost = c;
on_hand = o;
}
void show();
};
void inventory::show()
{
cout item;
cout ": $" cost;
cout " On hand: " on hand "\n";
int main()
inventory ob("wrench", 4.95, 4);
ob.show();
return 0;

116

, inventoryO -
show() - item, cost onjiand . , - . , "",
.
. , this , . , :
// this
#include <iostream>
^include <cstring>
using namespace std;
class inventory {
char item[20] ;
double cost;
int on_hand;
public:
inventory (char *i, double c,
{
strcpy (this->item, i) ; //
this->cost = ;
//
this->on_hand = ;
//
1
void show {) ;
\.

int o)

this

void inventory: : show ()


{
cout this->item; // this

cout ": $" this->cost;


cout " On hand: " this->on_hand "\n";
int

main()

inventory ob( "wrench", 4 . 9 5 ,

4);

ob . show ( ) ;
return 0;

- ob
this. , show() :

4. ,

117

cost = 123.23;
thi 3 ->cost = 123.23;

.
, , C++,
this , ,
, ,
.
this no-.
. 6. , - .

]
1. ,
, this.
ftinclude <iostream>
using namespace std;
class myclass {
int a, b;
public:
myclass(int n, int m) { a = n; b = m; }
int add() { return a + b; }
void s h o w ( ) ;
void m y c l a s s : : s h o w ( ) ;
int t;

t = add(); // -
cout t <<"\n";

int main ()
myclass ob(10, 14);
ob.show ();
return 0;

118

C++

4.4. new delete



mallocQ, free(). C++
. new, delete.
:
p-var = new type;
delete p-var;

type ~ , , a p-var . New ,


,
type. delete ,
. delete
.
,
: new ,
. (
. , .)
Standart C++
new
. , . , ,
, new
, .
, new , Standart C++.
C++ ,
new . ,
new .
, new ,
. , new . ,
Microsoft Visual C++
new , Borland C++ . -

4. ,

119

new
Standart C++, , , .
, new
, -,
. new
. , new , , new
.

new , . , , new, ,
. new, .
: new,
.
new delete malloc()
free() , . -,
new . sizeof,
, . . -, new . ,
, , ,
mallocQ (. ). -, new, delete ,
, . -,
,
. ,
<cstdlib>.

mallocf)
, void *( mallocf) ) .

120

C++

, .
C++ . maflocf) . , C++ .
, new delete,
malloc() free().

1. :
// new delete
^include <iostream>
using namespace std;
int main()
int *p;

p = new int; //
!p) (
cout " \n";
return 1;
,

* = 1000;
cout " , : " * "\";
delete p; //
return 0;

, new . ,
, new .
2. , :
//
# include <iostream>
using namespace std;
class samp {
int i , j ;
public:
void set_ij (int a, int b) { i = a; j = b; }

4. ,

121

int get_product() { return i * j ; }


int
f

main()
samp *p;
p = new samp; //
if(!p) 1
cout " \";
return 1;

c->v .-. ; j { 4, 5 ) ;

out " :" p->getjproduct() "\n";


return 0;

]
1. , new float, long char. .
delete
.
2. .
new, .
3. new ?

4.5.
new delete
new
delete. -, . -, .
, new:
p-var = new type (_) ;

122_

C++


new:
p-var = new type [size];

p-var size . -
,
.

delete:
delete [] p-var;

.
, p-var, .

delete .
C++.
.

i J
1. :
//
#include <iostream>
using namespace std;
int mainO
{

int *p;
p = new int (9); //
9

cout " \";


return 1;

cout " , : " * "\";

4. ,

123

delete p; //
return 0;

, 9,
, .
2. :
//
#include <iostream>
using namespace std;
class samp {
int i, j;
public:
sampfint a, int b) { i = a; j = b;
int get_product(} { return i * j ; }

int

main(}

samp *p;
p = new samp(6, 5); //
cout " \";
return 1;

cout " :" p->get_product() "\";


delete p;
return 0;

samp ,
6 5,
3. :
// new delete
#include <iostream>
using namespace std;
int main ( )

int *p;
p = new int [5]; // 5

124
I/ ,

iff!p) !
cout " \" ;
return 1;
int i ;

for(i=0;

delete [] p; //
return 0;

}
:

,
,
,
,
,

[0]:
[1]:
[2]:
[3]:
[4]:

1
2
3
4

4. :
//
^include <iostream>
using namespace std;
class samp (
int i, j;
public:
void set_ij(int a, int b) f i = a; j = b; }
int get_product() { return i*j; }
I;
int main()
i

samp *p;
int i ;
p = new samp [10]; //
cout " \n";
return 1;

C++

4. ,

125

for (i-0; i<10;


p [ i ] .set_ij (i,

for(i=0;
cout " [" i "] :
cout p[i] .get_product ( ) "\n";
delete [] p;
return 0;

[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]

:
:
:
:
:
:
:
:
:
:

1
4
9
16
25
36
49
64
81

5. samp
, ,
:
//
^include <iostream>
using namespace std;
class samp {
int i, j;
public:
void set_ij (int a, int b) { i = a; j - b; }
-sampO { cout " ... \n"; }
int get_product ( ) { return i*j; }
int main ( )
/
samp *p;
int i;
p = new samp [10]; //
cout " \";
return 1;

7 26

C++

for(i=0; i
cout " [" i "] :";
cout p[i] .get_product (} "\n";
}
delete [J p;
return 0;

:
[0] :
[ 1 ] :
[2] :
[3] :
[4] :
[5] :
[ 6 ] :
[7] :
[8] :
[9] :
. . .
. . .
...
. . .
. . .
. . .
. . .
. . .
. . .
. . .

1
4
9
16
25
3
49
64
81

, samp
.

1. , new.
char *p;
- ( char *) rnalloc(lOO) ;
// ...

strcpyip, " ");


. .

4. ,

127

2. new, ,
double 123.0987.

4.6.
C++ , (reference). ,
. . -,
. -, . ,
. , .
, - . ,
- , , ( ):
^include <iostream>
using namespace std;
void f ( i n t *n) ; // -
int main ( )
int i = 0;

cout " i: " i ' n V ;


return 0;
}

void f (int *n)


(

*n = 100; // 100 ,
//
\

f() 100 , . f()


main() i. ,
f() i 100.
, (call by
reference). -

128

C++

. C++ - . , , .
-:
^include <iostream>
using namespace std;
void f (int &n) ; // -
int main ( )
(
int i = 0;

f (i);
cout " i: " i 'n\';
return 0;

// f ( ) -
void f ( i n t &n)
(
// , *
= 100; // 100 ,
// f{)

. -, - (&).
, f(). , ,
*. , f(), , f(). ,

100 ,
f(), i. ,
f() &.
, f() -,
.
, - , .
( ) &. , -

4.

129

, -,
( ) *. ,
-
.
: , , . ,

f(), -
i main(). , , ( i).
- ( ) -.
-,
. . -,
, - , . -,
,
. ,
.

'

"^

1. ,
.
swapargs() ,
:
^include <iostream>
using namespace std;
void swapargs(int &x, int y) ;
int

main()

i
int i, j;
i = 10;
j = 19;

cout "i: " i ", ";


cout "j: " j "\n";
swapargs(i, j) ;

730

C++
cout " : ";
cout "i: " i ", ";
cout "j: " j "\n";
return 0;

void swapargs(int &x, int &y}


{
int t;

t = x;
x = y;

swapargsQ
, :
void swapargsfint *x, int *y)
|
int t;

J- *
v .

* = *;
* = t;

, swapargs(),
*.
2. round()
double. .
^include <iostream>
^include <cmath>
using namespace std;
void round (double &num) ;
int main ( )
iouble i = 100.4;

:>ut i " ";


>und ( i ) ;
i_ .at i "\n";
= 10.9;
cout i " ";
round ( i ) ;
cout i "\n";

4.

131

return 0;

void round (double snum)


{
double frac;
double val;
// num
frac = modf(num, &val);
ifffrac < 0.5) num = val;
else num = val + 1.0;

rou n (1 0
modf(). ; , modf().

!
^> neg(),
1.
. : - -.
.
2. ?
//
#include <iostream>
using namespace std;
void triple(double Snum);
int
{

main()
double d = 7 . 0 ;

tripleUd) ;
cout d;
return 0;
//
void triple(double Snum}

132

C++

num = 3 * num;

3. -.

4.7.
3, ,
. ,
.
(, ).
. ( , 5,
.) ,
. , : , .

, , .
(.), (->}.

1. ,
, , myclass() f() :
^include <iostream>
using namespace std;
class myclass {
int who;

public:
myclass(int n) (
who = n;
cout " " who "\n";

4.

133

~myclass() { cout " " who "\n"; }


int id(} { return who; }

)i
1 1
void f(myclass )
{
cout "" o . i d l ) "\n";
int main()
{
myclass x(l) ;

f Cx);
return 0;

:
1
1
1
1

, : , f() 1,
.
, , , f()
:
#include <iostream>
using namespace std;
class myclass {
int who;
public:
myclass(int n) {
who = n;
cout " " who "\n";
}
~myclass() { cout " " who "\n"; }
int id (){ return who; }
};
//
void f(myclass So)

134

C++

I I , -
cout "" o . i d ( ) "\";
int main(}
myclass ( 1 ) ;

fix);
return 0;

:
1
1
1


(.), (->).

1. ? ,
- .
//
^include <iostream>
^include <cstring>
^include <cstdlib>
using namespace std;
class strtype {
char *p;
public:
strtype (char *s) ;
-strtype { ) { delete [ ] p; }
char *get{) { return p; }
strtype: istrtype (char *s)
(

int 1;

4.

735

1 = s t r l e n ( s ) + 1;
= new char [1] ;
if(!p) (

cout " \";


exit (1) ;
}

strcpy{p, s);
}

void show(strtype x)
I

char *s;
s = x.get () ;
cout s "\n";

int
(

main()
strtype {"") , b ( "")
show (a) ;
show(b) ;
return 0;

4.8.

. 6,

.
. .

1. , , :
//
^include <iostream>
using namespace std;

136

C++

int sf 0 ;
int x;
int main ( )
{

f ( ) = 100; / / 100 , f ()
cout x "\n";
return 0;
//
int &f (}
{

return x; //
}

f() .

return ;

, ( ). , main()
f()

= 100;

100 , f()
.
, f() . f()
,
, . ()
( ),
100.
2. , ,
, . , , f():
//
int &f{)
{
int x; //
return ; //

f()
. , ,
f(), .

4 . ,

C++
. , -, , .
3. (bounded array). , C++
. , . C++
(automatic bounds checking).
. ,
.
:
//
#include <iostream>
#include <cstdlib>
using namespace std;
class array {
int size;
char *p;
public:
array (int num) ;
~ array () ( delete [] p; }
char sput {int i) ;
char get (int i) ;
array: rarray (int num)
{

p = new char [num] ;


ifUp) (
cout " \";
exit (1) ;
}
size = num;
I

//
char Sarray: :put (int i)

138

C++

| i>=size) {
cout ", ! ! !\n"
exit(l) ;

}
return p[i]; // p[i]

// -
char array: :get (int i)

if (i<0 ! I i>=size) {
cout ", ! ! !\n"
exit (1) ;

}
return p[i]; //
int main{)
,
array a {10} ;
a.put(3) = 'X';
a.put(2) = 'R';
cout a.get{3) a. get (2);
cout "\n";
/* ,
*/
a.put(ll) = '! ';
return 0;

, . ,
put() ,
i. , i, ,
,
. get(), , .
(safe array).
, , new . .
, ,
, C++.

4, ,

139

,
. , : .
,
.

1. , (2x3)
. , .
2. ? , ?
int fif;

int *x;
= f();

4.9.

, (independent reference). ,
.
, .

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

, .
. .
.
, , .

440

C++

, .

1. :
^include <iostream>
using namespace std;
int main()
{
int x;
int &ref = x; //
x = 10;
ref = 10;

//
//

ref = 100;
// 100
cout ' ' ref <<"\n";
return 0;

ref . ref .
2. . ,
:
const int &ref = 10;

,
.

]
1. .

4. ,


:
1. a_type. , ,
.
.
class a_type {
double a, b;
public:
a_type(double x, double y) {
a = x;
b = y;

}
void show() { cout a ' ' b "\n"; }

);
2. , .
3. this?
4. new delete.
malloc() free()?
5. ?
?
6. recipQ, - double. .
.


, .
1. .
?
2. 2 strtype,
. ( ) , new
delete.

142

C++

#include <iostream>
^include <cstring>
linclude <cstdlib>
using namespace std;
class strtype {
char *p;
int len;
public:
strtype (char *ptr) ;
-strtype {) ;
void showf) ;
);
strtype: : strtype (char *ptr)
{
len = strlen(ptr)
p=(char *} malloc (len+1) ;
if(ip) {
cout " \";
exit{l) ;
strcpy(p, ptr) ;
strtype : : -strtype ( )
{
cout " \";
free (p) ;
}
void strtype: : show ()
{
cout p " : " len;
cout "\n";
}
int main { )
(
strtype si {" ") , 2(" C++");
si .show () ;
s2 . show ( ) ;
return 0;

3. ,
.

.
, ,
. : , ,
, .


,
.
1. ? ?
2. , new
float int. , delete.
3. new,
? .
4. . , 1 10 .
Class samp (
int x;
public:
sump(int i) { x = n; }
int getx () [ return x; }

5. -.
6. , ?

144

C++

7. mag(), mim ,
order:
void mag(long Snum, long order);

, num 4, order 2,
mag() num
400. , ,
.

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

,
. , ol , 2 . ,
,
samp . , , ,
samp.
.
^include <iostream>
using namespace std;
class myclass {
int x;
public:
//
myclass{} { x = 0; J //

5.

745

myclass(int n) { x = n; } //
int g e t x ( ) { return x; }

};
int

main()
myclass ol(10); //
myclass o2; //
cout "ol: " ol.getxO '\';
cout "2: " o2,getx() '\';
return 0;

2.
, , . , ,
, , .
(
, .) ,
, , ,
.
, myclass 1 :
myclass ob{10);
myclass ob[5];

( ),
,
, .
, , . ,
myclass;
, :
^include <iostream>
using namespace std;
class myclass {
int x;
public:
//
myclass!) { x = 0; } //

146

C++

myclass(int n) { x = n; } //
int getx() { return x; }

int main ()
{
myclass ol[10]; //
//
myclass o2[10] = {1,2,3,4,5,6,7,8,9,10};

int i;

for(i=0; i<10; i++} {


cout "ol[ " i "]:" ol [i] . getx ( ) ;
cout ' \n' ;
cout "o2 [ " i "]:" o2 [i] . getx ( ) ;
cout '\n' ;

return 0;

ol .
2 , .
3. ,

. , , , .
datcQ .
, .
^include <iostream>
#include <cstdio> // sscanfO
using namespace std;
class date {
int day, month, year;
public:
date (char *str) ;
date (int m, int d, int y) {
day = d;
month = m;
year = y,}
void show() {

cout month ' / ' day ' / ' ;

5.

14_7_

cout year ' \ n ' ;

};
date::date{char *str)
{
sscanf(str, "%d%*c%d%*c%d", smonth, day, Syear);
}
int main (}
{
//
date sdate("ll/l/92");
//
date idatefll, I, 92) ;
sdate.showO ;
idate.show();
return 0;

date(), ,
, ,
. , date , .
date -
, , ,
.
,
. , , . ,
date()
- . date() time_t ( )
. (. , .)
4. , ,

. ,
. , , . , ,
:
^include <iostream>
using namespace std;

148

C++

class myclass {
int x;
public:
//
myclass () { x = 0; } //
myclass (int n) { x = n; } //
int getx{) ( return x; }
void setx(int n) { x = n; }
1;
int mainO
myclass *p;
myclass ob(10); //
p = new myclass [10]; //
if(!p) {
cout " \";
return 1;

int i ;
// ob
for(i=0; i<10; i++) p[i] = ob;
for(i=0;
cout "p[ " i "]:" p[i].getx
cout '\n' ;

return 0;
I

myclass(),
, new .

1. :
class strtype {
char *p;
int len;
public:
char *getstring() { return p; }
int getlength{) { return len; }

5.

149

. . 255 (
new), len 255. .
, ,
. , . ,
, , ,
.
2. 2, 2.1, 2 . , stopwatch
( ) clockQ. ,
.
3. ,
.

5.2.

(copy constructor).
, . ,
.
, . , (. . )
, . ,
. ,
, ,
. , ,
! ,
, ,
. ,
.
, . ,
. ( -

150

C++

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



,
.

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

:
_ (const _ Sobj)
//

5.

151

obj ,
. , myclass. myclass,
myclass:
myclass x=y;
fund ();
y=func2();

//
//
//


.
, funcZQ

1. , . "" ,
. new, -.
/* "" .
/ ,
,

V
^include <iostrearn>
#include <cstdlib>
using namespace std;
class array {
int *p;
int size;
publ i :
array (int sz)

//

p=new int [sz] ;


if(!p) exitU);
size=sz;
cout " \" ;
~ array ( ) (delete [] p ; }
//
array{const array &a) ;
void put(int i, int j) {
if(i>=0 5& i<size) p[i]=j;
}

152

C++

int get(int i) {
return p[i] ;

/*
,
. ,
, ,
:
*/
array: :array (const array &a) {
int i;
size = a. size;
p=new int [a. size] ;
//
if(!p) exit(l);
f o r ( i = 0 ; i<a.size; i++) p [ i ] = a . p [ i ] ; / /
cout " \";

int ma in ()

array num(10);
//
int i ;
//
for(i=0; i<10; i--) num. put (i, i) ;
//
for (i=9; i>=0; i ) cout num.get(i);
cout "\n";
//
array x=num;
//
//
for (i=0; i<10; i--) cout x.get(i);
return 0;

,
. ,
.
num , . ( , . num.p
.) ,
array x= , ! ( , . num.p
.)

5.

153

. ,
:
array a (10};
array b(10) ;
b = ; //

b = .
2. ,
, ,
, :
/ /
#include <iostream>
^include <cstring>
^include <cstdlib>
using namespace std;
class strtype (
char *p;
public:
strtype(char *s);
-strtype() {delete [] p;}
char *get() (return p;}
strtype:: strtypefchar *s)

int 1;
l=strlen(s)+1;
p=new char[1];
cout " \";
exit(1} ;
strcpy(p, s);

void show(strtype x)
char *s;
s=x.get() ;
cout s "\n";
1

154

C++

int main ()
{

strtype a ("Hello"), b("There");


show (a) ;
show(b) ;
return 0;
, strtype show(),
( ) . , , . ,
, ,
..
, ,
. .

strtype, strtype . ,
:
/* ,
strtype
*/
# include <iostream>

# include <cstring>
# include <cstdlib>
using namespace std;
class strtype {
char *p;
public:

strtype(char *s) ;
//
strtype (const strtype &o) ;
//
~strtype(} {delete [] p; }
//
char *get() {return p; }

};
//
strtype: : strtype (char *s)
(
int 1;
l=strlen(s) +1;
p=new char [1] ;
if(!p) (
cout " \";

5.

155

exit (1) ;

}
strcpyfp, ) ;

}
//

strtype: istrtype (const strtype &o)


t
int 1;
l=strlen(o.p) +1;
p=new charfl] ; //
if(!p) {
cout " \";
exit(l) ;
}
strcpy (, .} ; //

}
void show (strtype x)
{
char *s;
s=x.get () ;
cout s "\n";

}
int mainO
{
strtype a ("Hello"], b( "There");
show (a) ;
show(b) ;

return 0;
, show() , , . ( ), ,
.

[
]
1. ,
, (
, ). , :

156

C++

. , .
^include <iostream>
using namespace std;
class myclass {
public:
myclass () ;
myclass (const myclass &o) ;
myclass f ( ) ;

//
myclass : :myclass ( )
{
cout " \";
}
/ /
myclass: imyclass (const myclass So)
{
cout " ";
i
//
myclass myclass: :f()
{
myclass temp;
return temp;

int main!)
{
myclass obj;
obj=obj.f{);
return 0;

2. , , .
//
#include <iostream>

5.

157

^include <cstdlib>
using namespace std;
class rayclass {
int *p;
public:
myclass (int i) ;
~myclass() (delete p; }
friend int getval (myclass o) ;

myclass: :myclass(int i)
{
p=new int;
if(!p) {
cout " \";
exit(l) ;

int getval(myclass o)
return *o.p; / /

int

main()
myclass a ( l } , b ( 2 ) ;

cout getval(a) " " getval(b);


cout "\n";
cout getval(a) " " getval(b);
return 0;
J

3. , .

5.3. overload
C++
overload. overload , , , .

158

__

C++

overload:
overload ;

_ . . ,
,
timer():
overload timer ();

overload C++ .

5.4.
C++ ,
(default argument). ,
, . , .
,
, , . ,
0:
void f l i n t = , int = 0 ) ;

, . . -, . , .
b . ,
f() ,
b . ,
f() :
f(); // b
f(10); // 10, b
f(10, 99); // 10, b 99

5.

J59

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

1. :
//
#include <iostream>
using namespace std;
void f ( i n t a = 0, int b = 0)
{
cout "a: " a ", b: " b;
cout ' \ n r ;
int main ()

f<10);
f(10, 9 9 ) ;

return 0;
}

, :
: , :
: 10, :
: 10, : 99

160

C++

, ,
. , f() :
void f(int a - 0, int b) // ! b
//
{
cout ": " ", : " ;
cout ' \' ;

2. , , ,
rect_area(). .
/*
*/
#include <iostream>
us ing name space s td ;
//
double rect_area (double length, double width)
{
return length * width;

//
double rect_arsa (double 'length)
{
return length * length;
)
int
{

main()
cout " 10 x 5.8 : ";
cout rect_area(10.0, 5.8) '\n';
cout " 10 x 10 : " ;
cout rect_area(10.0) '\n';
return 0;

rect_area() . .
.
, rect_area().

5.

161

, , . ,
rect_area(). ,
length. :
/*
*/
^include <iostream>
using namespace std;
//
double rect_area (double length, double width = 0)

1
if {! width) width = length;
return length * width;

int
{

raainO
cout " 10 x 5.8 : ";
cout rect_area(10.0, 5 . 8 ) ' \ n ' ;
cout " 10 x 10 : ";
cout rect_area(10.0) ' \ n ' ;

width .
, .
(, .) , rect_area() , ,
length.
,
. (, , -.)
3. ,
. , , , .
. , :
^include <iostrearri>
using namespace std;

162

C++

class myclass {
int x;

public:
/*

*/

myclass(int n = 0) ( x = n; }
int getxf) ( return x; }
int main()
{
myclass ol(10); //
myclass o2; //
cout "ol: " ol.getxO '\';
cout "2: " o2.getx() '\;
return 0;

, n
, , , , ,
.
4. ,
. , , . ,
print() . how ignore, , . how upper, .
how lower, . how , 1,
.
^include <iostream>
tinclude <cctype>
using namespace std;
const int ignore = 0;
const int upper = 1;
const int lower = 2;
void print(char *s, int how = -1) ;
int main()
f

print ( " \n", ignore) ;

5,

63

print (" \n", upper);


print (" \") ; //
print (" \n", lower) ;
print (" \") ; //
//
return 0;

/* .
, .
*/
void print (char *s, int how)
{
static int oldcase = ignore;
// ,
if (how<0) how = oldcase;
while (*g) {
switch (how) {
case upper: cout (char) toupper(*s);
break;
case lower: cout (char) tolower(*s);
break;
default:- cout *s;

1
oldcase = how;


5. .
.
, , . , :
myclass(const myclass Sobj, int x=0) (
//

164

C++

,
, .
.
6. ,
. , '
.
, . , , ,
, , , . ,
, ,
, -
. , ,
,
.
,
,
.

)
1. C++ strtol(), :
long strtol(const char *start,

const **end, int base);

,
start, . base .
end ,
. , . base 2 38.
10.
mystrtol(), ,
strtolQ, 10 base .
( strtolQ .
<cstdlib>.) ,
.
2. ?
char *f(char *p, int x = 0, char *q);

3. C++ ,
-

5.

165

. ,
myclreolQ, ,
. , . ,
. , .
4. ?
int f(int count, int max = count);

5.5.
. (ambiguity), ,
, - .
.
.
, .

^^'


C++. , , ( ) , ,
. (type
promotion). ,
, putchar(), , , int.
. , , :
//
^include <iostreani>
using namespace std;
float f (float i)
t
return i / 2.0;

__

166

__

C++

double f (double i)
I
return i / 3.0;

\
int main ( )
{
float x = 10.09;
double = 10.09;
cout f(x); //
// f (float)
cout f (y) ; //
// f (double)
cout f(10); //
// 10?
// double float?
return 0;

main(), f(), double, float. ,


? f(float)
f(double)? ( !) ,
"" int float, double. , .
,
. , f(), .
2. , . , , C++ .
//
^include <iostream>
using namespace std;
void f (unsigned char c)
cout c;

}
void f (char c)
{
cout c;

5.

767

int main ()
(

f 1};
f{86); // f(} ?
return 0;

f() 86,
, : f(unsigned char) f(char).
, .
3. ,
, ,
-, - . C++ , . ,
. :
//
^include <iostream>
using namespace std;
int f { i n t a, int b)
{
return a + b;
//
int f f i n t a, int &b)
{
return a b;
J

int

main()

cout f ( x , y) ; // f ( } ?
return 0;

f(x, ) ,
.
, ,
, ,
.
4. ,

. :

168

C++

II ,
//
^include <iostream>
using namespace std;
int

f f i n t a)
return a * a;

int f { i n t a, int b = 0)
return a * b;

int

mainO
cout f(10, 2); // f(int, int)
cout f(10); // ,
// f(int, int) f(int)???
return 0;

f(10, 2) . ,
f() f(10) , .

1. , . .
, .

5.6.

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

5.

169

, ,
zap() :
- zap;


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

,
space(). , count.
- , ch.
main() . , . , .
/*

*/

^include <iostream>
using namespace std;
// count
void space(int count)
{
for(; count; count ) cout ' ';
// count ,
// ch
void space(int count, char ch)
(
fort; count; count ) cout ch;

170

C++

int main )
f

/* . */
void (*fpl) (int) ;
/*
. */
void (*fp2) (int, char);
fpl = space; // space (int)
fp2 space; // space (int, char)
fpl (22); // 22
cout "|\n";
fp2(30, 'x'); // 30
cout "|\n";
return 0;

, ,
fpl fp2, ,
.
,
, ,
. , .
, ,
.

]
1. . , .
int d i f f i n t a,
{

int b)

return a b;

float dif (float a, float b)


{
return a b;

5.

171




:
1. date() 5.1, 3 ,
time_t. (, time_t ,
C++.)
2. ?
class samp {
int ;
public:
samp (int i)

int

{ a = i;

rnain()

(
samp x, (10) ;

3. ,
.
4. ?
5. ?
6. , overload,
.
7. , ?
8. reverse() .
str , ,
,
. count
str . count ,
reverse() .
9. ?
char *wordwrap(char *str, int size = 0, char ch) ;

172

++

10. .
11. ?
void compute(double *num, int divisor = 1);
void compute(double *num);
// ...
compute(&x);

12. , ?



, .
1. orderQ, -
. , .
. , , order(), ,
. ,
int = 1, = 0;

order(x, ) ;

0, 1.
2. ?
int f ( i n t a) ;
int f ( i n t &a) ;

3. ,
.
4. , , main() .
(: samp().)
class samp {
int a;

5.
public:
//
int get_a() { return a; }

int ma in
samp ob(88); // 88
samp obarray[10]; // 10-

5. , .

173

C++:
. C++
. .


,
.
1. , ,
, . ( 0.)
class myclass {
int x,y;
public:
myclass (int i, int j) ( x = i; = j; }

2. 1, ,
myclassQ
3. ?
int f {int = , double balance) ;

4. ?
void f (int a) ;
void f (int &a) ;

5. ? ?

776

__

___

C++

. . ?
class test {
char *p;
int *q;
int count ;
public:
test (char *x, int *y, int c) {
p = x;

q -y;
count = c;

7. ?

6.1.
. , . .
,
, , . .
, . , ,
, .
- (operator function).
, -
, .
- -.
- . -
.
- :
-_: *_: : opera tor # ( )
{

//

- ,
. ( - .) - -

6.

177

# . , +, operator*. - -
.
. , . -,
. , / ,
.
C++ .
, :

, . ( .* .)
, C++ :
[], (),
new delete, . () -> ().
.
-, ,
. ( ,
).
: , /. , /
.
- ,
. ,
, . , / , 300
" C++", .
, - .
/ .
, . ,
- , - .
, - .

178

C++

6.2.
- ,
. ,
.
- , this.
, -
. , , ,
.

1. +
coord. X,Y.
// 4 coord
^include <iostream>
using namespace std;

class coord {
int x,y; //
public:
coord () { x = 0; y= 0; }
coord{int i, int j) { x = i; = j; }
void get_xy(int &i, int j ) { i = x; j = y; }
coord operator-*- (coord ob2) ;

I / + coord
coord coord: :operator+ (coord ob2)
{

coord temp;
temp.x = x +ob2.x;
temp. = +2.;
return temp;

int main ()
coord ol (10, 10), o2(5, 3), o3;
int x, y;
o3 = ol + o2; //
// operator-*- ()

6.

179

.get_xy(x, ) ;
cout "(01 + 2) X: " ", Y: " "\";
return 0;

(ol + 2) X: 15, Y: 13

. operator+() coord, X , Y . ,
temp operator+() . ,
. temp .
( ) + , . ,
. , 10-, 14,
10, 4 . , .
, operator+ coord,
,
coord . ,
= ol + 2;

, ol + 2 , . ,
. , coord,
,
. , :
= ol + 2 + ol + ;

, -, , , ,
-
. ( . 6.3 "
" .)
. coord -,
:
(ol 4 2).get x y ( x , ) ;

180

C++

, operator+(),
. , .
2. coord =.
// +, = coord
^include <iostream>
using namespace std;
class coord {
int x, ; //
public:
coord () { x = 0; y= 0; }
coord (int i, int j) { x = i; = j ; }
void get_xy(int &i, int &j} { i = x; j = y; }
coord operator-f (coord ob2) ;
coord operator- (coord ob2);
coord operator= (coord ob2) ;

// + coord
coord coord: :operator+ (coord ob2)
(
coord temp;
terap.x = x + ob2.x;
temp, = -f ob2.y;
return temp;

}
// coord
coord coord: : operator- (coord ob2}
{
coord temp;
temp . x = x - ob2 . x ;
temp. = ob2.y;
return temp;

// = coord
coord coord: :operator=( coord ob2)
{
x = ob2 . x ;
= ob2.y;

6.

181

return *this; // ,
//

>
,,
int main{)
{
coord ol (10, 10), o2(5, 3), ;
int x, y;

o3 = ol + o2; //
// operator* ()
o3.get_xy !x, ) ;
cout "(ol + 2) X: " x ", Y: " "\n";

= ol 2; //
// operator- ()
o3.get_xy (, ) ;
cout " (ol - 2) X: " ", Y: " "\";
= ol; // - operator= ( }
o3.get_xy (, ) ;
cout "( = ol) X: " ", Y: " "\";
return 0;
operator () operator+().
,
. operator+()
. ( + +.)
. , , .
operator (), :

2 . ;

,
.
- . , (. . ,
) .
. -, *this.

182

, operator=() , .
. , C++ ( ):
a = b = c = d = 0 ;

*this, coord. ,
:
2 = ol;

, , , , . =
, , , *this.
3. ,
, , ,
, -. , + , coord:
// + ob-fob,
// ob+int
#include <iostream>
using namespace std;
class coord {
int x, ; //
public:
coord0 { x = 0; = 0; }
coord (int i, int j) { x = i; = j; }
void get_xy(int fii, int &j) { i = x; j = y; }
coord operator+(coord ob2); // ob + ob
coord operator+(int i); // ob + int

// + coord
coord coord::operators(coord ob2)
{
coord temp;
temp.x = x +ob2.x;
temp. = +2.;
return temp;

6.

183

II + ob-t-int
coord coord::operator+(int i)
{
coord temp;
temp.x = x + i;
temp. = + i;
return temp;

int main()
coord ol (10, 10), o2(5, 3), o3;
int x, y;

o3 = ol + o2; //
// operator+ (coord)
o3.get_xy (x, ) ;
cout "(ol + o2) X: " x ", Y: " "\n";
o3 = ol + 100; //
// operator+(int)
o3.get_xy (x, y};
cout "(ol + 100) X: " x ", Y: " "\n";
return 0;
: -
,
,
. :
, , , . , ?
= 19 + ol; // int + ob

. operator+(int i) ,
.
. ( .)
4. - -. , + coord :
// + coord,
coord coord: :operator-t-(coord &ob2)

184

C++

coord temp;
temp.x = x + ob2.x;
temp. = + ob2.y;

return temp;

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

]
1. coord * /. .
2. %. ?
coord coord::operator%(coord ob)
{

double i;
cout " : ";

cin i;
i
3

cout " " i " ";


cout sqr(i);

, - - coord.
.

6.

185

6.3.


.
, , -,
, - . ,
true false. ,
- true false,
, .

i/'

8 C++ - , . 1,
true false.
.
, true false.

1. == &&:
II == && coord
^include <iostream>
using namespace std;
class coord {
int x, ; //
public:
coord() { x - 0; y= 0; }
coord(int i, int j) { x = i; = j; }
void get_xy(int &i, int &j) { i = x; j = y; }
int operator^ (coord ob2);
int operators &(coord ob2);
// == coord
int coord::operator==(coord ob2)
{
return x==ob2.x && y==ob2.y;

186

C++

// && coord
int coord::operators&(coord ob2)
{
return (x && ob2.x) && ( && ob2.y);
\
int main()
t
coord ol(10, 10), o2{5, 3}, o3(10, 10), o4 (0, 0);
if(ol==o2) cout "ol o2\n";
else cout "ol o2\n";
if(ol==o3) cout "ol o3\n";
else cout "ol \";
if(ol&&o2) cout "ol && o2 \";
else cout "ol && o2 \";
if(ol&o4) cout "ol && o4 \";
else cout "ol 5& o4 \";
return 0;

1. coord < >.

6.4.
, , , . -
. ,
-. .

'

1. coord
(++):
// ++ coord
^include <iostream>
using namespace std;

6.

767

class coord {
int x, ; //
public:
coord () { = 0; = 0; }
coord (int i, int j) { x = i; = j; }
void get_xy(int Si, int Sj) { i = x; j = y; }
coord operator-n- () ;
};
// ++ coord
coord coord: :operator++ ()

return *this;
int main { }
coord o l U O , 10) ;
int x, y;
--ol; //
ol.get_xy(x, ) ;
cout "(++ol) X: " x ", Y: " "\n";
return 0;

, , .
, , :
2 = ++ol;
, ,
.
.
2. C++
++ .
:
-H-ol;

C++ ,
.

188

C++

operator++().
, . :
coord coord: :operator++ (int notused);

++ ,
operator++(). ++ ,
opera tor++ (int notused). notused 0. , ,
- .
3. , C++ ,
. , , , , . :
, , . , , :
// coord
^include <iostream>
using namespace std;
class coord {
int x, ; //
public:
coord (J { x = 0; y= 0; }
coord(int i, int j) { x = i; = j; }
void get_xy{int &i, int &j ) { i = x; j = y; }
coord operator- {coord ob2); //
coord operator- (); //
}t
/ / coord
coord coord: : operator- (coord ob2)
1
coord temp;
terap.x = x ob2.x;
temp. = ob2.y;
return temp;

// coord
coord coord: : operator- ( )

6.

__

189

return *this;
}

int main ()
{
coord ol(10, 10), o 2 ( 5 , 7 ) ;
int x, y;
ol = ol o2; //
ol.get_xy {x, y) ;
cout " ( O l - o 2 ) X: " x ", Y: " " \ n " ;
ol = -ol; //
ol.get_xy (x, y) ;
cout " ( - o l ) X: " x ", Y: " " \ n " ;
return 0;

, ,
. , . . ,

operator (coord ob2), operator ()

]
1. coord. .
2. + coord ,
( ), . +
.

6.5. -
, , -, . , this
. , - , . ,
-

190

C++

-, , .


. - .

1. operator+() coord
:
// + coord
//
#include <iostream>
using namespace std;
class coord {
int x, ; //
public:
coord() { x = 0; y= 0; }
coord (int i, int j) 1 x = i; = j; }
void get_xy(int si, int & j) { i = x; j = y; }
friend coord operator*(coord obi, coord ob2);
);
// +
coord operator+(coord obi, coord ob2)
{
coord temp;
temp.x = obl.x + ob2.x;
temp. = obi. + ob2.y;
return temp;
int main()
{
coord ol(10, 10), o2(5, 3), o3;
int x, y;
o3 = ol + o2; //
// operator+{)

6.

191

o3.get_xy(, ) ;
cout "(ol + 2) X: " ", Y: " " \ " ;

return 0;

, ,
.
2.
, .
-, , . ,
-, , ,
, .

. , - , ,
:
= 2 + 10; //
= 10 + 2; //

, ,
, ,
, , . , .
, - . , , ,
. ,
, .
:
// -
^include <iostream>
using namespace std;
class coord {
int , ; //
public:
coord() { x = 0; y= 0; }
coord(int i, int j) { x = i ; y = j ; }
void get_xy(int Si, int &j) { i = x; j = y; }
friend coord operator+(coord obi, int i);
friend coord operator+(int i, coord obi);

192

C++

II + , ob + int
coord operator-*-(coord obi, int i)
coord temp;
temp.x - obl.x + i;
temp. = obi. + i;
return temp;
}

// + int + ob
coord operator-Hint i, coord obi)
{
coord temp;
temp.x = obl.x + i;
temp. = obi. + i;
return temp;
int main!)
{
coord ol (10, 10) ;
int x, y;
ol = ol + 1 0 ; / / +

ol .get_xy (x, y) ;
cout " ( o l + 10) X: " x ", Y: " "\n";

ol = 99 + ol; // +
ol.get_xy (x, y) ;
cout "(99 + ol) X: " x ", Y: " "\n";
return 0;
- :

ol = ol + 10;
ol = 99 + ol;
3. - ++ - ,
this. , , .
.
, - , . -

6.

/93

(. . this),
.
-, , ,
, . ,
++.
// ++
^include <iostrearn>
using namespace std;
class coord {
int x, ; //
public:
coord () ( x = 0; y= 0; }
coord (int i, int j) { x = i; = j; }
void get_xy(int Si, int &j) { i = x; j = y; }
friend coord operator++ (coord &ob) ;

// ++
coord operator+-f (coord Sob) //
//
ob,x++;
.+-;
return ob; // ,
//

int ma in ()
coord ol(10, 10) ;
int x, y;
++ol; // ol
ol.get_xy (x, y) ;
cout "(++ol) X: " x ", : " "\n";
return 0;

, -
,
-. . , -

194

C++


coord:

coord operator*-*- (coord Sob}; //


coord operator++(coord Sob, int notused); //

+4- , coord
operatoH-+(coord &ob). , ++ ,
coord operator++(coord &ob, int notused).
notused 0.

!|
leHUflj
1. / coord
.
2. coord ,
coord . : ob * int int * ob.
3. , 2 -.
, - coord. , .

6.6.

, . , , ,
, , . , , operator=().
, . 3
. .

I ]
1. strtype,
. =
, .

6.

195

^include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class strtype {
char *p;
int len;
public:
strtype (char *s) ;
-strtype () {
cout " " (unsigned) p ' \ n ' ;
delete []p;
)
char *get() { return p; }
strtype &operator= (strtype &ob) ;
};
strtype: : strtype (char *s)
{
int 1;
1 = strlen(s) + 1;
p = new char [1] ;
if(!p) {
cout " \";
exit(l) ;
}
len = 1;
strcpy (p, s) ;

/ / .
strtype fistrtype: :operator= (strtype &ob)

//
if {len < ob.len) { //
delete!] p;
p = new char [ob.len];
if(!p) {
cout " \";
exit ( 1 ) ;

len = ob.len;
strcpy (p, ob.p);
return *this;

/96

__

C++

int ma in ()
(
strtype ("") , b ("") ;
cout a . g e t O ' \ n ' ;
cout b . g e t O ' \ n ' ;

a = b; //
cout a.getO ' \ n ' ;
cout b.getO ' \ n ' ;
return 0;
,
. ,

. ,
. ,
1.
operator=(). -, - .
, .
, ,
.
, , . , . -
.
operator=() , , . , -. ,
. ,
,
, ( )
. ,
,
.

5,
, .
, .
, ,

6.

197

.
, C++
. ~ C++.

, . .
size. put(), get(),
. . ,

. (
.)
class dynarray {
int *p;
int size;
public:
dynarray(int s); // s
int Sput(int i); // i
int get(int i}; // i
// operator={)

6.7.
[]
, ,
[]. C++ []
. [] -.
- operator!] ():
__: : opera tor [] (int )
II

...

, - operator[](), , , int.

198

C++

, [], , :
0[9]

operator[]():
.operator[](9)

, operator[]() . this , .

^i/"

1.
arraytype. . operator[]() , .
# include <iostream>
using namespace std;
const int SIZE = 5;
class arraytype {
int a [SIZE] ;
public:
arraytype ( ) (
int i ;
for (i=o; i<SIZE; i-H-) a[i] = i;
}
int operator [] {int i) { return a[i]; }

int main ( )
{
arraytype ob;
int i;
for{i=0; i<SIZE; i
cout ob[i]
return 0;

:
0 1 2 3 4

6.

199


.
2. operator[]() , [] ,
=. . .
ttinclude <iostream>
using namespace std;
const int SIZE = 5;

class arraytype {
int a [SIZE];
public:
arraytype (} {
int i ;
for {i=o; i<SIZE; i++) a[i] = i;
int Separator [] (int i)

{ return a [ i ] ;

int main ( )
arraytype ob;

int i;
f o r ( i = 0 ; i<SIZE; i
cout o b f i j " ";
cout "\n";
// 10
f o r { i = 0 ; i<SIZE; i-H-}
ob[i] = ob[i]+10; // [] =
f o r ( i = 0 ; i<SIZE; i+-t-)
cout ob[i] " ";
return 0;

:
0 1 2 3 4
10 11 12 13 14

operator[]() i, [] -

200

C++

. (,
.) , arraytype
, .
3. [] -
.
,
get() put(). [] . , ,
, . . [], , .
operator[]()
. , operator[]()
. , , .
//
#include <iostream>
finclude <cstdlib>
using namespace std;
const int SIZE = 5;
class arraytype {
int a[SIZE];
public:
arraytype () {
int i ;
for (i=o; i<SIZE; i++) a [ i ] = i;
int &operator[] (int i) ;

// arraytype
int fiarraytype: : operator [] (int i)

cout " ";


cout i " . \
exit (1) ;
}
return a [i] ;

6.

201

int main ()
arraytype ob;
int i;

//
for{i=0; i<S!ZE; i++)
cout ob[i] " ";
/* ,
SIZE+100 */
ob[SIZE+100] = 99; // !!!
return 0;

, operator[](),

ob[SIZE+100] = 99;

, -
.
[] ,
, ,
.
. ,
. , - C++
. , ,
, .

1. 1 6.6 , strtype
[]. . , []
. , .
2. 1 6.6 , []
.
get() put() [].

202

\
,

C++



~~2^


:
1. coord ,
:
ob integer
ob integer
,
.
2.
class three_d (
int , , z;
public:
three_d(int i,
{

int j,

int 3t)

x = i; = j ; z = k;
}

three_d() { x = 0; - 0; z = 0; }
void get (int &i, int sj, int &k)
{
i = x; j = y; k = z;

+, , ++ . (
.)
3. 2 , - - -. (.
.)
4. -
- ?
5. , .
6. operator=() ?
7. + three_d 2 ,
:

6.

203

ob + int;
int + ob;

8. ==, != || three_d
2.
9. [].



, .
1. strtype, :
+

<, > ==

.
, , ( ), .

.
.
OOP,
C++. C++ , , 10,
OOP .
, ,
: ,
protected, ,
, .


,
. 1. - ?
2. , , ?
3. ?
?
4. , ,
-:
^include <iostrearn>
using namespace std;
class array {
int nums[10];
public:
array (} ;

206

C++

void set(int n[10]);


void show();
array operator+(array ob2) ;
array operator-(array ob2} ;
int operator==(array ob2);

};
array::array()

int i ;
for{i = 0; i < 10; i++) nums[i] - 0;

1
void array::set(int *n)
{
int i ;

for(i = 0 ; i < 10; i++) nums[i] = n [ i ] ;


}
void array::show()

{
int i;
for(i = 0; i < 10; i++)
cout numsfi] ' ' ;
cout "\n";

}
// -
int main()
{
array
J ol, o2, o3;

int i[10] - {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };


ol.set (i);
o2.set(i);

o3 = ol + o2;
o3.show();
o3 = ol - o3;
o3.show() ;
if{ol==o2) cout "ol o2\n";
else cout "ol 2\";
if(ol==o3} cout "ol o3\n";
else cout "ol \";
return 0;

7.

207

+ .
. == true, , false.
5. 4 ,
.
6. 4, ++
, . (
++ :.)
7. , ,
?

7.1.

,
:
class : __ (

// . . .
J

cn_docmyna : public, private


protected. protected . public
private.
(access specifier) , (base class) (derived class).

public, . private,
.
.
, private,
, .

208

C++

. class,
.

struct, .
, .

1.
( public):
^include <iostream>
using namespace std;
class base {
int x;
public:
void setx{int n) { x = n; }
void showx() ( cout x '\n'; }
/ /
class derived: public base {
int y;
public:

void setyfint n) { = n; }
void showy () { cout '\n'; }

};
int main()
{
derived ob;
ob.setx(lO); //
ob.sety(20); //
ob.showx(); //
ob.showyO; //
return 0;

, base ,
base setx() showx() derived

7.

209

. ,
main
2. , ,
. ,
derived :
class base {
int ;
public :
void setx(int n) { x = n; }
void ghowxf) { cout x '\n'; }

//
class derived: public base {
int y;
public:
void sety(int n) { = n; }
/* ,

*/
r
void show_sum(} { cout + '\n ; } // ! ! !
void showy {) { cout '\n'; }

derived ,
base. , ,
, .
3. 1. base , . . private.
, ,
.
/ /
tinclude <iostream>
using namespace std;
class base {
int x;
public:
void s e t x f i n t n} ( x = n; }
void showx{) { cout x ' \ n ' ; }

210

_+

/!
class derived: private base {
int ;
public:
void setyfint n) { = n; }
r
void showy () { cout \n'; }

int raain()
(
derived ob;
ob.setx(lO); //
ob.sety(20); //
ob.showxi); //
ob. showy (); //
return 0;

() ,
showx() setx() .
, showxQ setx() base -
,
. , base
. derived
. , :
base base_ob;
base_ob.setx (1) ; // , base_ob
// base

setx() , setx()
base,
4. ,
private
, . , :
//
^include <iostream>
using namespace std;
class base (
int x;
public :
void setx(int n) { x = n; }

7.

211

void showxO { cout x '\n'; }

};
//
class derived: private base {
int y;
public:
// setx derived
void setxy(int n, int m) { setx(n); = ; }
// showx derived
void showxyO { showxf); cout '\n'; }
};
int main ()
{
derived ob;
o b . s e t x y U O , 20) ;
ob.showxy();
return 0;
}
.

showx() setx()
, , .

1. :
ttinclude <iostream>
using namespace std;
class mybase {
int a, b;
public:
int c;
void setab{int i, int j ) ( a = i; b = j ; }
void getab(int Si, int &j ) { i = a; j = b; }
class derivedl: pablic mybase {

212

C++

class derived2: private mybase (

int rnainO
derivedl ol;
derived2 o2;
int i, j;

// ...

mainQ?
A.

ol.getab(i, j ) ;

B.

2.getab(i, j ) ;

C.

o l . c = 10;

D.

o 2 . c = 10;

2. , ? , ?
3. , , . .

7.2.
,
. ,
,
. , ,
, ,
. C++
protected ().
protected private
:
.
.
protected , ( ) .
:

7.

213

class {
//
protected: //
//
public:
//


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

.
(, ,
.)
protected .

1. ,
:
finclude <iostream>
using namespace std;
class samp (
// ,
int ;
protected: // samp
int b;
public:
int ;
samp(int n, int m) { a = n; b = m; }
int geta(} { return a; }
int getb() { return b; }

};
int main{)
{
samp ob(10, 20);

214

__

__

C++

// ob.b = 99; !
ob.c = 30; // !
// samp
cout ob.geta() ' ';
cout ob.getbO ' ' ob.c r\n';
return 0;

, , main(), b
- samp.
2. , ,
:
^include <iostream>
using namespace std;
class base {
protected:
// base,
int a,b;
//
public:
void setab(int n, int m) { a = n; b = m; }
class derived: public base {
int c;
public :
void setc(int n) ( = n; }
// b base
void showabc 0 {
cout ' ' b ' ' '\n';

int main ( )
(
derived ob;
/* b ,
base derived

ob.setab(l, 2) ;
ob.setc (3) ;
ob. showabc () ;
return 0;

7.

215

base derived , derived.


.
3. , ,

. , base ,
:
//
^include <iostream>
using namespace std;
class base {
protected:
// base,
int a,b;
//
public:
void setab(int n, int m) { a = n; b = m; }
};
class derived: protected base ( II base
//
int ;
public:
void setcfint n} { = n; }
// b base
void showabc () {

cout a ' ' b ' ' '\n';


\
int main()
derived ob;
// : setab{)
// base
ob.setab(l, 2); // setab()
ob.setc (3) ;
ob . showabc ( ) ;
return 0;

, base ,
derived main()
.

216

C++

1. ,
? , ?
2. , protected?
3. 1 7.1, b myclass
( ), ,
- ? ,
?

7.3. ,

, / . .
, , . ,
.
:
.

. " " ,
, .
.
,
, . , . ,
,
.

.
. ,
. . -,
. ,

7.

217

, . :
__(-) : _ (_)
//


. ,
.

1. ,
:
^include <iostream>
using namespace std;

class base {
public:
b a s e ( ) { cout " \"; }
~base ( ) { cout " \"; }

class derived: public base (


public:

derived() ( cout " \"; }


-derived () ( cout " "; }
int main ()

{
derived ;
return 0;

:




, , .

218

__

__

2.
:
linclude <:iostream>
using namespace std;
class base {
public:
base() { cout " \"; }
-base () { cout " \"; }
class derived: public base {
int j ;
public:

derived(int n) {
cout " \";
j = n;
}
~derived{) { cout " \"; }
void showj() { cout j '\n'; }

};
int main()
/

derived (10) ;
. showj ( ) ;
return 0;
,
.
3.
.
,
.
#include <iostream>
using namespace std;
class base {
int i;
public:
base {int n) {
cout " \";
i - n;

7.

2)9

-base () { cout " \"; }


void show!() ( cout i ' \ n ' ; }

class derived: public base {


int j ;
public:
derived{int n} : base (n) { //
/ /
cout " ";
j = n;
}
~derived() { cout " \
)
void showj() { cout j '\n'; }

);
int main ()
t
derived (10) ;
o.showi ( ) ;
o.showj () ;
return 0;
.
, n ( )
derived() base().
4.
. , , ,
. , . ,
,
, - :
#include <iostream>
using namespace std;
class base {
int- i;

public :
base (int n) {
cout " \" ;
i = n;
\

220

C++
-base() { cout " \"; )
void showi() { cout i '\n'; }

class derived: public base {


int j ;
public:
derivedfint n, int m) : base (m) { //
//
cout " \";
j = ;
}
~derived() { cout " \

}
void showj() { cout j '\n'; }

};
int main()

{
derived (10, 20) ;
. showi () ;
o.showj () ;
return 0;

5. -
, . ,
. , derived() . base():
class base {
int i;
public:
base (int n) {
cout " \";
i = ;
}
-base () { cout " \"; }
void showi () ( cout i *\n'; }

class derived: public base {


int j ;
public:
derived(int n) : base(n) { //

7.

221

cout " \";


j = 0; //
}

)
-derived() { cout " \";

void showj(} { cout j '\n'; }

[]
&^

1. myderived.

mybase. , myderived() len .
ttinclude <iostream>
# include <cstring>
using namespace std;
class rnybase {
char str[80] ;
public :
mybasefchar *s) { strcpy(str, s) ; }
char * g e t ( ) { return str; }
class myderived: public mybase {
int len;
public:
// myderived ()
int getlenf) ( return len; }

void showf) ( cout get() '\n'; }


};
int main ()
{
myderived ob ("") ;
ob . show ( ) ;
cout ob.getlen() '\n';
return 0;

2. ,
() truck().
vehicle. ()

222

C++

passengers, truck() loadlimit.


^include <iostream>
using namespace std;
//
class vehicle {
int num_wheels;
int range;
public:
vehicle(int w, int r)
num_wheels = w; range = r;
void showv()
,
cout " " num_wheels '\n';
cout "" range '\n';

J;
class car: public vehicle {
int passengers;
public:
// ()
void show()
showv();
cout "" passengers '\n';

class truck: public vehicle {


int loadlimit;
public:
// truck {)
void ahow()
{
showv {) ;

cout "" loadlimit ' \n ' ;

int main ()
(
car c(5, 4, 500) ;
truck t (30000, 12, 1200);

\7._

223

cout " :\";


.show();
cout ":\";

t. show () ;
return 0;
() truck()
:
car ob(passengers, wheels, range);
truck ob(loadlimit, wheels, range);

7.4.
, . -, ,
. , (indirect)
. (,
, .)
-, . . ,
.
, ,
, ,
. ( .) . , 1
Dl, a D1 D2, 1 , D1, , , D2. .
,
:
class __.:

_ __1,
_^> .2,

. . . , _-

{
I I . . .

224

C++

__1 ... UMR_6a3oeozo_tuiaccaN , _ ,


. ,
,
.
.
,
, , :
_ (_) : ! ( ) ,
__2 (_) ,
. . . , _(
{
// ...

__! ... uMR_6o3oeoto_KnaccaN .


,

.

1. ,
. ,
D2 1.
//
^include <iostream>
using namespace std;
class Bl {
int a;
public:
B l ( i n t x) { a = x; }
int geta!) { return a; }

//
class Dl: public Bl {
int b;
public:
Dl(int x, int y): Bl() // Bl

225

7,
(

11

= ;

int getbO t return b; }

//
//
class D2: public Dl {
int ;
public:
D2 (int x, int y, int z) : Dl{y, z) //

// Dl
{

= x;

/* , D2
1 Dl */
void show ( ) {
cout geta() ' ' getb() ' ';
cout ' \n ' ;

int main ( )
{
D2 ob(l, 2, 3);
ob.showf) ;
// geta() getb ( )

cout ob.geta{) ' ' ob.getb{) '\n';


return 0;

ob.showQ 3 2 1.
1 D2. ,
D2 D1 1.
, . , D1
1, geta()
D1 D2.
, , .
.

226

C++

D1

D2
,
C++. ,
, .
C++
, . , C++.
2. , :
^include <iostream>
using namespace std;
//
class Bl {
int a;
public:
Bl(int x) { a = x; }
int geta() { return a; }

//
class B2 {
int b;
public:
B2 (int x}
f
b = x;
}
int getbO { return b; }
//
class D: public Bl, public B2 {
int c;

'

227

public:
// z
// 1 2
D{int x, int / int z) : Bl(z), B2(y)

{
= ;
/* , D
1 2

*/

int

void show ( ) {
cout getaO ' ' g e t b ( ) ' ';
cout ' \ n ' ;

main()

D ob(l, 2, 3) ;
ob.show() ;
return 0;

D 1 2. :

Bl

B2

D
3. , ,
:
#include <iostream>
using namespace std;
class Bl {
public:
B l { } { cout " 1\";
-Bl() { cout " 1\";

1;

}
}

228

C++

class B2 {
int b;
public:
B2 ( ) ( cout " 2\"; }
~2 ( ) { cout " 2\"; )
//
class D: public Bl, public B2 {
public:
D() { cout " D\n"; }
~D() { cout " D\n"; }

};
int main ()
{
D ob;

return 0;

1
2
D
D
2
1

, ,
, .
.

^
1. ? ( ,
.)
^include <iostream>
using namespace std;
class A {
public:
A() { cout " \"; }
~-A{) { cout " \"; }

7.

229

class {
public:
() { cout " \"; }
~() { cout " \"; }

};
class : public A, public (
public:
(} ( cout " \"; }
~() { cout " \"; }

};
int main ( )
{
ob;
return 0;

2. , ,
k () ().
^include <iostreani>
using namespace std;
class A {
int i;
public:

A{int a) { i = a; }
class {
int j;
public:
{int a) { j = a; }
class C: public A, public {
int k;
public:
/* C(),
k () */

7.5.

. ,
, :

C++

230

! 2.
! 2. , !,
2. ,
, .
,
,
!, , 2? C++ ,
. , , (virtual base class).
,
,
,
.
( )
,
. virtual.

' "

' $

\, derived3
base .
//
^include <iostreara>
using namespace std;

7.

231

class base (
public:

int i ;

1;
// base
class derivedl: virtual public base {
public:
int j ;
// base
class derived2: virtual public base {
public:
int k;

/* derivedS derivedl,
derived2. derived3
base
*/
class derived3: public derivedl, public derived2 {
public:
int product (} { return i * j * k; }

int m a i n f )
{
derivedS ob;
// ,
// base
ob.i 10;
ob . j = 3 ;
ob.k = 5;
cout " " ob.productf) '\n';
return 0;

derivedl derived! base ,


ob.i - 10;

. (.
1.)
2. ,
,

232

C++

. ,
:
derivecil ob;
ob.i = 100;


, .
,
. (
) .

1. 1 virtual . .
2. , .




:
1. building
, .
house, building
. office,
building . (.
. , ,
.)
2. ,
? ?
, ?
3. , protected. ( :
.)
4. , ? ?

7.

233

5. , ,
:
^include <iostream>
using namespace std;
class planet {
protected:
double distance; //
int revolve;
//
public:
planet (double d, int r) { distance = d; revolve = r; }
class earth: public planet {
double circumference; //
public:
/* earth (double d, int r) .
planet ,
{:
= 2 * 3.1416.)
V
/* show() */
int main ()

earth , 365);
ob.show( ) ;
return 0;

6. :
/* vehicle.
. . :
*/
^include <iostream>
using namespace std;
//
Class vehicle {
int num_wheels;
int range;
public:
vehicle(int w, int r}
num wheels = w; range = r;

234

________

C++

void showvO
{
cout " " nuin_wheels ' \ n ' ;
r
cout "" range \ n ' ;

enum motor {gas, electric, diesel};


class motorized: public vehicle {
enum motor mtr;
public:
motorized {enum motor m, int w, int r) : vehicle (w, r)
{
mtr = m;
}
void showmO {
cout ":";
switch (mtr) {
case gas: cout " \";
break;
case electric: cout " \";
break;
case diesel: cout "";
break;

class road_use: public vehicle {


int passengers;
public:
road__use (int p, int w, int r} : vehicle(w, r)
t
passengers - p;
1
void showr()
(
cout "" passengers '\n';

enum steering {power, rack_pinion, manual};


class car: public motorized, public road_use {
enum steering strng;
public:
car(enum steering s, enum motor m, int w, int r, int p}:

7,

235

road_use(p, w, r ) , motorized(m, w, r), vehicle(w, r)


{

strng = s;

void show() {
s h o w v f ) ; showr(); showm();
cout ":";
switch(strng) (
case power: cout " \";
break;
case rack_pinion: cout " \";
break;
case manual: cout " ";

break;
I

};

int main()
car c(power, gas,

4,

500,

5);

.show();
return 0;
}



, .
1. 6 7,
(, , ),
switch
motorised. ?
2. , , , .
? , .
3. coord .

236

__

C++

quad, , .
.
/* +, = coord.
coord quad */
^include <iostream>
using namespace std;
class coord {
public:
int x, ; //
coord {) { x = 0; - 0; }
coord { int i, int j) { x = i; = j; }
void get_xy(int fii, int fij) { i = x; j = y; }
coord operator+ (coord ob2);
coord operator- {coord ob2);
coord operator=( coord ob2};

// + coord
coord coord: :operator+ (coord ob2)
{
coord temp;
cout " operator+ {) \n";
temp . x = x + ob2 . x ;
temp. = + ob2.y;
return temp;
// coord
coord coord: : operator- (coord ob2)

{
coord temp;
cout " operator- () \n";

temp.x = x ob2.x;
temp. = ob2.y;
return temp;
// = coord
coord coord: :operator= (coord ob2)

7.

237

{
cout " operator^ ()\";
= 2.;
= 2 . ;

return *this; //

class quad: public coord {


int quadrant;
public:
quad() { x = 0; = 0; quadrant =0; }
quad(int x; int y): coord(x, y)
if(x>=0 && y>=0) quadrant = 1;
else if(x<0 && y>=0) quadrant = 2;
else if(x<0 && y<0} quadrant = 3;
else quadrant = 4;
void showq()
cout " : " quadrant '\n';
quad operator=(coord ob2);

quad quad::operator=(coord ob2)


cout " operator=()\n";
x = ob2,x;
= ob2.;
if(x>=0 && y>=0} quadrant = 1;
else if(x<0 && y>=0) quadrant = 2;
else if(x<0 Sfi y<0) quadrant = 3;
else quadrant = 4;
return *this;
int main()
quad ol(10, 10), o2(15, 3), o3;
int x, y;
o3 = ol 4 o2; //

// operator-f()
o3.get_xy(x, y);
o3.showq();
cout "(ol + o2) X: " x ", Y: " "\n";

238_

= ol 2; //
o3.get_xy(x, ) ;
.showq();
cout " ( o l - 2) X: " ", Y: " "\n";
= ol; //
.get_xy(, );
o3.Showq();
cout "( = ol) X: " ", Y: " "\n";
return 0;

4. 3 ,
-.


/ C++

, , / C++.
. , C++ ,
/. , C++ -
/ . C++
- /. / C++
, .
/ C++
.
, - / C++ /.
, /
.
/ ( ), /
(/ 9).

/ C++: , C++,
, Standard C++.
. , / . ,
,
, . , / C++
.
, /
.
.
/ ,

240

C++

, Standard C++.
, /.
/ C++, /, /
/. ,
/ C++ , / .


,
.
1. . airship,
( ). airship
airplane balloon. airplane ( ) .
balloon ,
( ), (
). . (
, . ,
, .)
2. protected?
3. . ? ?
^include <iostream>
using namespace std;
class A {
public:
A{} { cout " A\n"; }
~A(} ( cout " \"; }
);
class : public A {
public:
B() { cout " \"; }
~B() { cout " \"; }

8.

C++

241

class : public {
public :
() { cout " \"; }
~ { cout " \"; }

1;

int main ( )

<

ob;
return 0;

4. .
?
class myclass: public A, public , public { . . .

5. :
^include <iostream>
using namespace std;
class base {

int i , j ;
public :
//
void showij (} { cout i ' ' j ' \ n ' ; }
class derived: public base {
int k;
public:
//
void show ( ) { cout k ' ' ; showij ( ) ; }

int main()
derived ob(l, 2, 3);
ob.show();
return 0;
J

6. , ,

.
( .)

C++

242

8.1.
/ C++
/ C++,
. / C++, , / , (streams). , , /,
. / , .
/ C++. /
, , , , / . ,
, ,
, .
, ,
: stdin, stdout stderr.
C++. C++,
:

cin

cout

clog

, , , cin, cout stdin, stdout stderr . cin cout .


clog . Standard
C++ wcin, wcout, wcerr wclog,
(16-) ,
.
(large character sets),
, , , .
,
. , /, .
1, C++ /
<iostream>. , /.
/ - (template classes).

8. / C++

243

-, (generic
classes), 11, . - , . -
,
. /, Standard C++
- /: 8- , (16-) . 8- ,
.
/ C++ , -.
bastcjstreambuf.
,
/ C++. , /,
basie_streambuf . ,
, basic_ios.
/ , ,
/.
basic_ios , basic_istream, basic_ostream basic_iostream. , /.
, /
: 8-
. - 8- ( ,
9).
-

8-

basic_streambuf

streambuf

basicjos

ios

basicjstream

istream

basic ostream
basicjostream

ostream
,
iostream

basic_fstream

fstream

basicjf stream

ifstream

basic_ofstream

ofstream

"

8-
,

C++

244

. , /,
/.
: ios , /.
ios. : , <iostream>.

8.2. /

, C++ . .
/ C++ ,
printfQ. , .
/ (format flags),

(bitmasks). ios
fmtflags, :
adjustfield

floatfield

right

skipws

basefield

hex

scientific

unitbuf

boolalpha

internal

showbase

uppercase

dec

left

showpoint

fixed

oct

showpos

ios
. ,
, , fmtflags
.
.
skipws,
(, ) . skipws , .
left,
, right,
. internal,
.
,
.

8. / C++

245

. .
oct ,
, hex .
, dec.
showbase .
, IF
Ox IF.
"" . ,
"" .
uppercase, .
showpos +
.
showpoint .
scientific . fixed . ,
.
umtbuf, (flush) (insertion operation).
boolalpha
true false.
, oct, dec hex,
basefield. ,
left, right internal, adjust field
, scientific fixed
floatfield.
setf().
ios. :
fratflags setf(fmtflags

);

, . (
.) , showpos :
_/.setf{ios::showpos);

/ ~ , .
-

246

. , showpos
ios. , , showpos . , showpos
.
, setf() ios
/. setfQ . setf() . , C++
. /
.
setfQ . OR. , setf()
cout showbase hex;
cout,setf(ios::showbase I ios::hex);

ios,
ios . , showbase ,
ios::showbase.

setfQ unsetfQ. - ios


.
:
void unsetf(fmtflags

);

, , . (
.)
-
. setf() unsetf() , ios -
flags(), .
:
fmtflags flags();

flags() , ,
/, . flags(). :
fmtflags flags(fmtflags t) ;

8. / C++

247

flags() / ;
. .

1. , .
^include <iostream>
using namespace std;
int

mainf)

//
cout 123.23 " " 100 '\' ;
cout 10 ' ' -10 '\';
cout 100.0 '\';
//
cout.unsetf(ios::dec); //
cout,setf{ios::hex \ ios::scientific);

cout 123.23 " " 100 '\n';


cout.setf(ios::showpos);
cout 10 ' ' -10 '\n';
cout.setf(ios::showpoint \ ios::fixed);
cout 100.0;
return 0;
}

:
123.23 100
10 -10
100
1.232300+02 64
a fffffff6
+100.000000

, showpos
. 10, . , , unsetfQ
dec. , , -

248

C++

dec . dec hex oct.


,
,
.
2. uppercase. uppercase, showbase hex. 88 .
"X" .
imsetf() uppercase 88. "" .
^include <iostream>
using namespace std;
int main ( )
tr
cout .unset f (ios: :dec) ;
cout .setffios: : uppercase | ios: ishowbase | ios::hex);
r

cout 88 \n';
cout. unsetf (ios: : uppercase) ;
cout B8 '\n';
return 0;

3. cout
flagsQ.
showflags(). .
^include <iostream>
using namespace std;
void showf lags ( ) ;

int main { )
{
//
showf lags () ;
cout. setf (ios: :oct I ios: : showbase I ios: : fixed) ;
showf lags () ;
return 0;

_. / C++
//
void showflags()
{
ios::fmtflags f;
f = cout.flags(); //
if(f & ios::skipws) cout "skipws ";
else cout "skipws \n";
if(f & ios::left} cout "left ";
else cout "left \";
if(f & ios::right) cout "right ";
else cout "right ";
if(f & ios::internal) cout "internal ";
else cout "internal ";
if(f & ios::dec) cout "dec ";
else cout "dec ";
if(f & ios::oct) cout "oct ";
else cout "oct ";
if(f & ios::hex) cout "hex ";
else cout "hex \";
if(f & ios::showbase) cout "showbase ";
else cout "showbase ";
if(f & ios::showpoint) cout "showpoint ";
else cout "showpoint ";
if (f & ios::showpos) cout "showpos ";
else cout "showpos ";
if(f ios::uppercase) cout "uppercase ";
else cout "uppercase ";
if(f & ios:scientific) cout "scientific ";
else cout "scientific ";
if(f & ios::fixed) cout "fixed ";
else cout "fixed ";
if (f & ios::unitbuf) cout "unitbuf ";
else cout "unitbuf ";
if(f & ios:iboolalpha) cout "boolalpha ";
else cout "boolalpha ";
cout "Xn";

249

250

C++

showflagsQ f fmtflags. fmtflags , f long. :


skipws
left
right
internal
dec
oct
hex
showbase
showpoint
showpos
uppercase
scientific
fixed
unitbuf
boolalpha
skipws
l e f t
right
internal
dec
oct
hex
showbase
showpoint
showpos
uppercase
scientific
fixed
unitbuf
boolalpha

4.
flags()- , showpos, showbase, oct right,
. flags() cout . showflagsQ
. ( ,
.)
^include <iostream>
using namespace std;
void showflagsf);

8. / C++
int

2_5_1_

mainf)

//
showf lags () ;
// showpos, showbase, cct right;
//
ios:ifmtflags f - ios::showpos | ios::showbase |
ios:: oct I ios::right;
cout.flags(f); //
showflags();
return 0;

!
IfiHUfl]
1. , cout ,
, , +. ,
.
2. , cout ,
. , "" .
3. , ,
showbase hex, 100,
.

8.3. width(), precision() fill()


ios -.
: , .
width(), precision() fill().
,
. width()
. :
streamsize width(strearasize w) ;

>,
. streamsize

252

C++

<iostream> .
, .
,
, , ( ) , . ,
, ,
. .

. precisionQ
. precisionQ:
streamsize precision(streamsize p);

( ) ,
.
, ,
. 1() . fill():
char fill(char ch);

fjllQ ch , .

1. ,
:
#include <iostream>
using namespace std;
int main()
{
cout.width(10); //
cout "" '\n'; //
cout.fill('%'); //
cout.width(10); //
cout "" '\'; //
cout.setf(ios::left); //
cout.width(10); //
cout "" '\'; //

8. / C++

253

cout.width(10); //
cout.precision(lO); // 10
cout 123.234567 \';
cout.width(lO); //
cout.precision(6); // 6
cout 123.234567 '\';
return 0;

%%%%
123.234567
123.235%%%

, .
2. , / C++ :
//
^include <iostream>
ftinclude <cmath>
using namespace std;
int main()
double x;
cout.precision(4);
cout "x

sqrt(x)

x 2\n\n";

for(x = 2.0; x <= 20.0; x++) {


cout.width(7);
COUt X " ";
cout.width(7);
cout sqrt(x) " ";
cout.width(7);
cout x*x "\n";
1

return 0;

:
x

sqrt(x)

x2

2
3

1.414
132

4
9

C++

254

4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

2
2. 236
2. 449
2. 646
2. 828
3
3. 162
3. 317
3.464
3. 606
3. 742
3. 873
4
4. 123
4 .243
4. 359
4. 472

16
25
36
49
64
81
100
121
144
169
196
225
256
289
324
361
400

.
)
1. 2 100. : , 10 , 5 .
2. center() :
void center (char *s) ;

.
width(). ,
80 . ( ,
80 .) ,
.
3. .
/ C++, .

8.4. /
/ C++
. / (I/O manipulators). ,
/ , , , ios.

8. / C++

255

/
/, , ios,
/.
. 8.1. , /
ios. ,
. 8.1, , Standard C++,
.
(, setw()),
<iomanip>.
.
, /. :
cout oct 100 hex 100;
cout setw(10) 100;

cout
100
. /

100 . 10, 100 . ,
( oct),
, , .
8.1. / Standard C++

boolalpha

boolalpha

dec

dec

endl

ends

NULL

fixed

fixed

flush

hex

hex

internal

internal

left

left

noboolalpha

boolalpha

C++

256

8. 1 ()

noshowbase

showbase

noshowpoint

showpoint

noshowpos

showpos

noskipws

skipws

nounitbuf

unitbuf

nouppercase

uppercase

oct

oct

resetiosflagsffmtflags f)

, f

right

right

scientific

scientific

setbase (int )

setfill(int /)

setiosf lag s(fmtf lags f)

, f

setprecision(int p)

setw(int w)

showbase

showbase

showpoint

showpoint

showpos

showpos

skipws

skipws

unitbuf

unitbuf

uppercase

uppercase

ws

, / ,
/, . / , ,
.
, ios , ,
.

, setiosflagsQ.
, - setf(). resetiosflags().
unsetfQ.

8. / C++

257

__^
\. /:
#include <iostream>
^include <iomanip>
using namespace std;
int main()
!
cout hex 100 endl;
cout oct 10 endl;
cout setfill('X') setw(lO);
cout 100 " " endl;
return 0;

:
64
12
144

2. ,
2 20. - /.
/*

*/
^include <iostream>
^include <iomanip>
^include <cmath>
using namespace std;
int main()
double x;
cout setprecision(4);
cout "x
sqrt(x)

xA2\n\n";

for(x = 2.0; x <= 20.0; x++) {


cout setw("7) x " ";
cout setw(7) sqrt(x) " ";
cout setw(7) x*x '\n';

258

C++

return 0;

3. / boolalpha. , boolalpha. , , . .
true false, 1 0 .
// boolalpha
^include <iostream>
using namespace std;
int main ( )
I
bool b;

cout " boolalpha: ";


b = true;
cout b " ";
b = false;
cout b endl;
cout " boolalpha: ";
b = true;
cout boolalpha b " ";
b = false;

cout b endl;
cout " : ";
cin boolalpha b; // true false

cout " : " b;


return 0;

:
boolalpha: 1
boolalpha: true f a l s e
: true
: true

, boolalpha, true
false. , boolalpha cin cout.
, boolalpha .

8. / C++

259

1. 1 2 8.3, ,
- , /.
2. 100
(). setiosflagsQ
3. , boolalpha.

8.5.
,
/ C++, / , /
. , .
C++ (insertion),
(insertion operator).
, (inserterfunction
inserter). , (inserts) . .
:
ostream &operator (ostream ustream, _ ;

{
//

return stream,-

ostream. ,
stream . (, ostream
ios.)
. (, , -). , stream, ostream.
, /:
cout 2 ;

. , , .

260

++

,

.
,
,
. . - , ,
this, , -. , . ,
- ,
. ,
, ,
, , .
-.
, -
C++, , , ,
, .
. ,
, ,
.
,
/, , .

1.^^
, coord, , :
//
// coord
#include <iostream>
using namespace std;
class coord {
int x, y;
public:
coordO ( x = 0; = 0; }
coord(int i, int j) { x = i; = j; }
friend ostream &operator(ostream sstreara, coord obj;

8. / C++

261

ostream &operator (ostream Sstream, coord ob)


p

stream ob.x ", " ob.y ' \ n ;


return stream;

int

main()

coord a(l, 1) , b(10, 23) ;


cout a b;
return 0;
:

1, 1
10, 23


:
, , .
/
stream, . , , ,
. ,
coord :
"
ostream &operator(ostream sstream, coord ob)
'

cout ob.x ", " ob.y ' \ n ' ;


return stream;


, cout. , .
, , , , , .
2. ,
coord. coord, .
// coord
#include <iostream>
using namespace std;

262

C++

class coord {
public:
int x, ; //
coord{) { x = 0; = 0; }
coord (int i, int j) { x = i; = j; }
// coord

ostream &operator (ostream sstream, coord ob)


{
stream ob.x ", " ob.y '\n';
return stream;
int main{)
{
coord ail, 1) , b(10, 23) ;

cout a b;
return 0;
3.


. , , - . ,
. , , .
, triangle,
. .
//
finclude <iostream>
using namespace std;
class triangle {
int height, base;
public:
triangle (int h, int b) { height = h; base= b; }
friend ostream &operator (ostream &stream, triangle ob) ;

J;
//
ostream soperator (ostream sstream, triangle ob)
i
int i, j, h, k;

8_._ / C++

263

i = j = ob.base 1;

for(h=ob.height - 1; h; h ) {
f o r ( k = i ; k; k )
stream ' ';
stream ' * ' ;

for(k=j - i - 1; k; k )
stream ' ' ;
stream ' * ' ;
i --;

stream ' \n' ;


for(k=0; k <ob.base; k++) stream '*;
stream '\n' ;
return stream;

int mainf)
triangle tl (5, 5 ) , t2 (10, 10), t3(12, 12)
cout tl;

cout endl t2 endl t3;


return 0;
,
"" /.
:
*

**

* *
* *

*****
*
*
*

* *
*

**
*
*

**********

*
*
*

*
*
*

*
*
*

*
*
*

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

264

++_

>>
1. strtype.
:
ftinclude <iostream>
^include <cstring>
^include <cstdlib>
using namespace std;
class strtype {
char *p;
int len;
public:
strtype(char *ptr);
-strtype () (delete [] p; }
friend ostream &operator (ostream &stream, strtype Sob);
strtype;:strtype(char *ptr)
len = strlen(ptr) + 1;
p = new char [len];
cout " \";
exit(l) ;

strcpy (p, ptr) ;

//
int main ()
strtype si (" "), 2(" C++");
coat si '\n' s2;
return 0;

2. show() :
^include <iostream>
using namespace std;
class planet {
protected:
double distance; //

8. / C++

265^

int revolve;
//
public:
planet(double d, int r) { distance = d; revolve = r; )

};
class earth: public planet {
double circumference; //
public:
earth{double d, int r): planet(d, r) (
circumference = 2 * distance * 3.1416;

/* show() ,

*/
void show () {
cout " : " distance '\';
cout " : " revolve '\';
cout " : " circumference '\';

};
int main()
earth ob(93000000, 365);
cout ob;
return 0;
3. , -.

8.6.
, ,
. C++ (extraction operator), , , (extractor). ,
. .
:
istream Separator (istream fistream, _ &-)
//

266

C++

return stream;

istream, .
. , .
, ,
-.
, .

'

*-

1. coord :
// coord
^include <iostream>
using namespace std;
class coord {
int x, y;
public:
coord() { x = 0; = 0; }
coord(int i, int j) { x = i; = j; }
friend ostream soperator (ostream Sstream, coord ob) ;
friend istream separator{istream Sstream, coord Sob);
ostream &operator (ostream sstream, coord ob)

stream ob.x ", " ob.y '\n';


return stream;
istream ^operator f istream sstream, coord &ob)
{

cout " : " ;


stream ob.x ob.y;
return stream;

int main()
{

coord a(l, 1) , b(10, 23) ;

cout a b;

C++

267

cin a;
cout a;

return 0;
, .
( ), ,

.
2. inventory (),
- ,
.
.
#include <iostream>
#include <cstring>
using namespace std;
class inventory {
char item[40]; //
int onhand;
//
double cost;
//
public:
inventory (char *i,

int o,

double c)

strcpy (item, i) ;
onhand = o;
cost = c;

}
friend ostreara &operator (ostream &stream, inventory obi;
friend istream &operator (istream ^stream, inventory &ob) ;
1;
ostream 5operator (ostream sstream, inventory ob)
{
stream ob.item ": " ob. onhand;
stream " $" ob.cost \';
return stream;
istream soperator (istream sstream, inventory &ob)
{
cout " : ";
stream ob.item;
cout " :
stream ob. onhand;

268

__

C++

cout " : " ;


stream ob.cost;
return stream;
int main ( )
inventory ob{ "hammer", 4, 12.55);
cout ob;
cin ob;

cout ob;
return 0;

]
1. strtype I
.
2. .
.




:
1. 100 , . (
ios.)
2. 1000.5364 20-
, , * . (
ios.)
3. 1 2 , /.
4. , cout .
- .

8. / C++

269

5.
:
class pwr (
int base;
int exponent;
double result; //
public:
pwr(int b, int e)
};
pwr::pwr(int b, int e)
f
base = b;
exponent = e;
result = 1;
for{; e; e ) result = result * base;

6. box . .
( .)



, .
1. stack,
. ,
.
ttinclude <iostream>
using namespace std;
^define SI2E 10
// stack
class stack {
char stck[SIZE]; //
int tos;
// -
public:
stack 0;
void pushfchar ch); //
char pop0;
//
1;

270

C++

I/
stack::stack()
{

tos=0;
//
void stack::push(char ch}
/

if (tos=SIZE) {
cout " ";
return;
}

stck[tos]=ch;
tos-f-+;
}

//
char stack::pop()
(

if (tos=~0) {
cout " ";
return 0; //
}
tos ;

return stckftos];
}

2. watch,
. ,
, .
.
3. , , , - . ,
, . .
class ft__to inches {

double feet;
double inches;
public:
void set (double f); {
feet - f;
inches = f * 12;
i

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

^*-^"^---

/ C++ Standard C++ C++.


/ ,
.


,
.
1. : "C++ "
40 (:)
.
2. 10/3
. -
ios.
3. , /.
4. ?
?

jTg

____

____

C++

5. . .
class date {
char date [9]; // : mm/dd/yy
public:
//

6.
/ ?
7. , C++?

9.1.


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

9. / C++

273

:
ostream ^ (ostream &)
(

(I
return ;
}

_
, ~ .
. ,
/.
, , , , , .
:
istream & , (istream )

{
//
return ;
I

, . .

, .
, .

1. . setup(), , 10,
, 4, *.
#include <iostream>
using namespace std;

274
ostream fisetup (ostrearn fistream)
f
stream.width(10);
stream.precision{4) ;
1
stream.filK *'} ;

return stream;
int main()
cout setup 123.1234^6:
return 0;
, setup / , .
2. .
, atn() note()
.
^include <iostream>
using namespace std;
// :

ostream Satn (ostream sstream)


i
stream ": ";

return stream;
}

// , :
ostream Snote (ostream ^stream)
{
stream ", : ";
return stream;
}
int main ( )
{
cout atn " ";
cout note " \";
return 0;
,
.

_9.

C++

275

3. getpass(),
:
#include ,<io3tream>
^include <cstring>
using namespace std;
//
istream bgetpass (istream Sstream)
{
cout ' \ a ' ; //
cout " : " ;
return stream;

int main ( )
{
char p w [ 8 0 ] ;
do {

cin getpass pw;


} while (strcmp(pw, ""));
cout " ";
return 0;

1. . td().
2. sethex(), uppercase
showbase. , resetQ, , sethex().
3. skipchar(), ,
.

9.2. /
,
/ . / , /.

276

C++

, , /,
. , - .
/,
<fstream>. ,
ifstream, ofstream fstream.
istream ostream. , istream ostream, ,
ios, ifstream,. ofstream
fstream , ios
( ).
C++ .
: , /.
, , -, . ifstream.
ofstream. , ,
fstream. ,
,
:
ifstream in; //
ofstream out; //
fstream io;
//

,
().
. :
void ifstream::open(const char *#_,
openmode = ios: : in) ;
void ofstream::open(const char * ,
openmode = ios: :out I ios: : trunc) ;
void fstream::open(const char *_,
Openmode = ios: : in | ios: : out) ;

UMxjpaUAa ,
. . openmode, ,
ios. :

ios
ios
ios
ios
ios

:app

:ate
: binary
: in
:out
: trunc


OR. , .

9. / C++

277

ios::app
? ,
. ios::ate .
ios::ate , ,
/ .
ios::in . ios::out
.
ios::binary . .
, , " / " . ,
. , ,
, , .
.
ios::trunc . ofstream

.
test:

ofstream mystream;
mystream.open("test");

() , , .
() , false.
, , :
if(!mystream) {
cout " \";
//
)

, , ().

is_open(), ifstream, ofstream fstream. :
bool is o p e n { ) ;

278

__

_+

, , . , , , mystream:
iff !mystream.is_open() ) {
cout " ";

openQ ,
, ifstream, ofstream
fstream , . , ,
(). :
ifstream mystream ("rnyfile") ; //

, - , , , false. , ,
(),
.
- close(). ,
, mystream, :
mystream. close ( ) ;

close() .
eof(), ios, , .
:
bool eof () ;

, ;
.
,
. ,
/, cm
cout , . ,
fprintfQ
fscanfQ. ,
. , ,
, ,

9. / C++

279

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

1. , , .
, :
tfinclude <iostream>
#include <fstream>
using namespace std;
int

main()

ofstream fout("test"); //
if{!font) {
cout " \";
return 1;

fout " !\";


fout 100 ' ' hex 100 endl;
fout .close () ;
if stream fin ("test"); //
if fin) {
cout " \";
return 1;
char str[80] ;
int i;
fin str i;
cout str ' ' i endl;

fin. close () ;

return 0;

280

__

___

__

C++

,
test. :
!
100 64

, /, ,
.
2. /. . $
. .
ftinclude <iostream>
^include <fstream>
using namespace std;
int main{int argc,

char * a r g v [ ] )

if(argc!=2) {
cout " <_>\" ;
return 1;

ofstream out (argv[l] ) ; // .


if (lout) {

cout " ";


return 1 ;

char str[80] ;

cout " ; S\n";


do {

cout ": ";


cin str;
out str endl;
} while (*str != 'S1) ;
out. close () ;
return 0;

3.
[. ,
eof(). ,

9. / C++

28?

fin skipws.
.
// |
ftinclude <iostrearn>
ttinclude <fstream>
using namespace std;
int main(int argc,

char * a r g v [ ] )

if (argc!=3) {
cout " <_> <_>\";
return 1 ;
}

ifstream fin(argv[l] ) ; //
ofstream fout (argv[2] ) ; //
if (lout) {
cout " ";
return 1;

if(!fin) {
cout " \" ;
return 1;
}

char ch;
f in. unsetf (ios: : skipws) ; //
while ( ! f i n , eof ( ) ) {
fin ch;
if (ch==' ') ch = ' | ';
if ( ! f i n . eof () ) fout ch;
fin. close () ;
fout. close () ;
return 0;

4. / C++ / Standard C++ , .


-, / C++ (') , .
. C++ .
-, / fstream

282

C++

ios::in ios::out. . fstream,


(). , / C++,
(), :
fstream mystream;
mystream.openC'test", i o s : : i n j i o s : : o u t ) ;

/ C++,
, fstream
.
. / openQ ,
ios::noncreate, , ios::noreplace,
, , . Standard C++
.

1. .
. , ?
2.
phone.
, 415 555-3423
, 213 555-2312
, 202 555-1111

3. . , , .
4. is_open?

9.3.
/
(. . ,
ASCII, . .) , .
"" , ,

9. / C++

283

, .
/ ""
(raw) /. C++
/.
.
/ get() put().
- put() ; - get() .
. get() put() .
:
istream figet(char ) ;
ostream &put(char );

get() .
.
false. put()
.

read() writeQ, . :
istream firead(char * , streamsize _) ;
ostream

fiwrite(const

char * ,

streamsize _);

readQ ,
_6 , . write() , , _
. streamsize
.
, _ , read() , , . ,
, - gcount(),
:
streamsize gcountO ;

,
.
, ,
, , -

284

C++

. , ios::binary .
, , , , . , ,
, ,
, .

1. . get().
^include <iostream>
ttinclude <fstream>
using namespace std;
int main(int argc,

char * a r g v [ ] )

char ch;
if(argc!=2)

cout ": <_>\";


return 1;
ifstream in(argv[lj, ios::in | ios : :binary) ;
i(!in) {
cout " \";
return 1 ;

while ( ! in,eof () )
in. get (ch) ;
cout ch;
in. close (} ;
return 0;

2.
put(). $.
#include <iostream>
#include <fstream>
using namespace std;

9. / C++

285

in.t main(int argc, char *argv[]}


char ch;
if(argc!=2)

cout ": < >\";


return 1;
ofstream out[argv[l], ios::out I ios:ibinary);
if (lout) {
cout " ";
return 1;
cout " $\";
do {
cout ": ";
cin.get(ch);
out.put(ch);
} while (ch!='$') ;
out.close ();
return 0;

, cin
get().
.
3. double test
wtite():
^include <iostreain>
#include <fstream>
#include <cstring>
using namespace std;
int main ()
{
ofstream out{"test", ios:rout I ios:ibinary};
if(lout) {
cout " ";
return 1;
}
double num = 100.45;
char str[] = " ";

286

C++
out.write((char *) &num, sizeof(double));
out.write(str, strlen(str));
out.close{):
return 0;

(char*) write() ,
. C++ , .

4. ,
3, read():
^include <iostream>
^include <fstreairt>
using namespace std;
\
int main ( )
{
ifstream in("test", i o s : : i n | ios : :binary) ;
cout " \";
return 1;

double num;
char str[80];
in.read( {char *) &num, sizeof (double) );
in. read(str, 15) ;
str[14] = '\0',cout num ' ' str;
in. close () ;
return 0;

,
read() , C++ .

9. / C++

287

5. double ,
. , .
// gcountO
^include <iostream>
ttinclude <fstrearn>
using namespace std;
int main()
ofstream out ("test", ios::out | ios: :binary) ;
if (lout) {
cout " \";
return 1 ;
double nums[4] = {1.1, 2.2, 3.3, 4.4};
out.write((char *) nums, sizeof(nums));
out. close (} ;
ifstream in("test", ios::in | ios::binary);
if(!in) {
cout " ";
return 1;
'

in.read((char *) snums, sizeof(nums));


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

cout numsfi] ' ';


cout '\n';
cout in.gcount() " \n";
in.close ();
return 0;
}

^'"S^p

1. 1 3 9.2 , get(), put(), read() / write(). (


, , , .)

288

C++

2. .
. .
class account {
int custnum;
char name[80];
double balance;
public:
account(int c, char *n, double b}
custnum = c;
strcpyiname, n);
balance = b;
//

};

9.4.
/
, get()
.
:
iatream figet(char *, strearasize _);
istream figet (char *, strearasize __,
char ) ;
int get();

get() , , , , _ I, .
, , get() .
, ,
.
get() , , , , _ 1, ,
, .
, , get() .
, ,
.
get() . EOF, .
get() getc() .

9. / C++

289

getline().
. :
istream figetline(char *, streamsize _);
istream ugetline(char * , streamsize ,
char ) ;

,
, , ,
_ 1, ,
. ,
, getline() .
, , .
, , , ,
_ 1, ,
. ,
, getline() .
, , .
, getlineQ get(5y$ep, _) %(9 _, )
get().
, ,
_ 1 ,
. get() getline() ,
gellineQ ,
get() .
peek(),
.
:
int peek();

, , EOF.
putbackQ,
,
. :
istream fiputback (char );

.

,
. . flush ()

C++

290

.
flush(), :
ostream fiflushO ;

flush() (, , ).

I. , ,
.
.
, , gctlinc() :
// getlineO
# include <iostream>
ftinclude <fstream>
using namespace std;
int

main()
char str [80];
cout " : ";
cin.getline (str, 79} ;
cout str ' \ n ' ;
return 0;

getline()
. getline() gets().
2. peek()
putback() , .
. . .
// p e e k ( )
^include <iostream>
ttinclude <fstream>
#include <cctype>
using namespace std;
int main ()

9. / C++

291

char ch;
ofstream out("test", ios::out | ios::binary);
.
if(lout) {
cout " \";
return 1;
}
char str[80], *p;
out 123 "this is a test" 23;
out "Hello there!" 99 "sdf" endl;
out.close{);
ifstream inC'test", ios::in | ios: :binary);
if(!in) {
cout " ";
return 1;
}
do {

p = str;
ch = in.peekj); //
if(isdigit(ch)) {
while(isdigit{*p=in.get())} p++; //
in.putback(*p); //
* = '\0'; //
cout ": " atoi(str);
}
else if(isalpha(ch)} { //
while(isalpha(*p=in.get())) p++;
in.putback(*p); //
* - '\0'; //
cout ": " str;
}
else in.getO; //
cout '\n';
} while(lin.eof());

in.close();
return 0;

1. I , getlineQ
get(). ?

292

C++

2. . getlineQ.
3. , flush().

9.5.
/ C++ (random access)
seekg() seekp(),
. :
istream fiseekg(off_type , seekdir );
ostream Sseekp(off_type , seekdir );

off_type -- , ios , . seekdir ,


ios :

ios:: beg

ios: :cur

ios: :end

/ C++ ,
. (get pointer),
, . (put pointer), ,
. . seekg() seekpQ
.
seekgQ
,
. seekp()
,
.
, , seekg() seekp(), . .
:

9. / C++

293

pos_type tellgO;
pos_type tellpO;
pos_type , ios .
,
tellgQ tellp(), seekgQ seekpQ. :
istream Sseekg{pos_type ) ;
ostream fiseekp(pos type ) ;

J
seekpQ. . ,
, , , ,
. :
.
^include <iostream>
^include <fstream>
^include <cstdlib>
using namespace std;
int mainlint argc, char *argv[])
{
if{argc!=4} {
cout ": <> <> <>\";
return 1;
fstream o u t ( a r g v [ l ] , i o s : : i n | ios::out | ios : : binary ) ;
if ( l o u t ) {
cout " \";
return 1;
out .seekp (atoi (arqv[2] ) , ios: :beg) ;
out .put (*argv[3] ) ;
out, close () ;
return 0;

294

__

++_

1, seekgQ , .
.
// seekg()
^include <iostream>
^include <fstream>
# include <cstdlib>
using namespace std;
int main(int argc, char *argv[]}
char ch;
if(argc!=3) {
cout ": <> <>\";
return 1;

if stream in(argv[l] , ios: :in I ios: : binary) ;


if(!in) {
cout " \";

return 1;
in.seekgfatoi (argv[2] ) , ios: :beg) ;

while (lin.eofO) {
in. get (ch) ;
cout ch;
in. close () ;
return 0;

]
1.
. (: . , .)
2. , . , "1234",
"2143". ( ,
.)

9. / C++

295

9.6. /
/ C++ /. /, iostate, ,
ios :

goodbit

eofbit

failbit
badbit

/
, iostate.
/.
-, rdstate(),
ios. :
iostate rdstateO;

. , ,
, ,
rdstate() goodbit
. .
, , ios:
bool bad () ;
bool eof () ;
bool fail () ;
bool good;

eof() . bad() ,
badbit. fail() ,
failbit. good() .
.

, .
!(), ios. :
void clear(iostate = ios::goodbit);

C++

296

goodbit ( ), . , .

""' " ''

%j/J

1. rdstateQ.
.
checkstatus().
^include <iostream>
finclude <fstream>
using namespace std;
void checkstatus(ifstream S i n ) ;
int m a i n f i n t argc,

char * a r g v [ ] )

if(argc!=2) {
cout ": <_>\";
return 1;
ifstream in(argv[l]);
if(!in) I
cout " ";
return 1;
char ;
while(in.get(c)) {
cout c;
checkstatus(in);
checkstatus (in); //
in.close () ;
return 0;
void checkstatus(ifstream sin)
ios::iostate i;
i = in.rdstate();
if(i & ios::eofbit)
cout " EOF\n";
else if(i & ios::failbit)
cout " /\";

9. / C++

297

else i f ( i S ios::badbit)
cout " /\n";

. while checkstatus(),
, ( EOF).
2. good()
:
tinclude <iostream>
#include <fstream>
using namespace std;
int main(int argc, char * a r g v [ ] )
'

char ch;
if(argc!=2) {
cout ": <_>\";
return 1;
}
ifstream in(argv[l]);
if (!in) {
cout " ";
return 1;

while(lin.eof0} {
in.get(ch);
//
if(!in.good() && lin.eof()) {
cout " / ... \"
return 1;
}
cout ch;

}
in.close();
return 0;

1. .

298

C++

9.7. /


.
/. C++ ,
, , , - , .
/ C++.
, / , /
. ""
/, , ,
. , , /, .

coord . , -
, .
tinclude <iostream>
ttinclude <fstream>
using namespace std;
class coord {
int x, y;
public:
coordfint i, int j) { x = i; = j; }
friend ostream operator(ostream &stream, coord ob);
friend istream &operator(istream &stream, coord Sob);
i;
ostream &operator (ostream Sstream, coord ob)
stream ob.x ' ' ob.y ' \ n ' ;
return stream;
istream soperator (istream Sstream, coord Sob)
{
stream ob.x ob.y;
return stream;

9.

int ma in ()

C++

299

coord ol(l, 2), o2(3, 4);


of stream out ("test");
if (lout) {
cout " ";
return 1;
out ol o2;

out. close (} ;
ifstream in ("test");
if(!in) {
cout " \"
return 1;
1
coord o3(0, 0), o4(0, 0) ;
in o3 o4;
cout o3 o4;
in. close () ;
return 0;

2. / /.
, , , , .
^include <iostream>
ttinclude <fstream>
ttinclude <iomanip>
using namespace std;
// :

ostream &atn(ostream Sstream)


{
stream ": ";
return stream;
}
// , :
ostream &note (ostream Sstream)
stream ", : ";

300

C++
return stream;

}
int main()
{
ofstream out("test"};
if(lout) {
cout " ";
return 1;
}
//
cout atn " \";
cout note " \";
//
out atn " \";
out note " \";
out.close();
return 0;

1. .



;:

"""l[^Nj


.
1.
20. .
2. , .
, . findalpha.
3. .
.

9. / C++

301

4. , , , .
5. , 3
4 .
6. ? ?



, .
1. inventory
. storeQ retrieveQ.
, . ,
, .
ttinclude <fstream>
ttinclude <iostream>
ttinclude <cstring>
using namespace std;
ttdefine SIZE 40
class inventory {
char itemfSIZE]; //
int onhand;
//
double cost;
//
public:
inventory(char *i, int o, double c);
strcpy(item, i);
onhand = o;
cost = c;
void store(fstream sstream);
void retrieve(fstream sstream);
friend ostream &operator (ostream sstream, inventory oV
friend istream &operator(istream sstream, inventory &ob) ;

};
ostream &operator (ostream &stream, inventory ob)
stream ob.item ": " ob.onhand;
stream " ." ob.cost '\n';

302

C++
return stream;

)
istream operator{istreara &stream, inventory sob)
{
cout " : ";
stream ob.item;
cout " : ";
stream ob.onhand;
cout " : ";
stream ob.cost;
return stream;

'

2. . stack
, .

10

C++:
(virtual functions). ,
(run-time polymorphism). , C++ . -,
. -, .
,
.

. .

,
.
1.
.
2. .
.
3. ,
. , , .
: , , .
4. , 234-
, out.
5. /
C++?

C++

304

6. / C++ '
/ .

10.1.
4 C++,
,
. : , ,
, ,
.
:
base *p; //
base base_ob; //
derived derived_ob; //

// ,
//
= &base_ob; //
//
//
= &derived_ob; //
,
, .
,
, .
, ""
, .
, . .
( , ,
.)
: , (. . ), . ,
, , . . .

10.

305

1. ,
:
//
#include <iostreara>
using namespace std;
class base {
int x;
public:
void setx(int i) { x = i; }
int getx0 { return x; }

class derived: public base {


int y;
public :
void sety(int i) { = i; }
int getyf) (return y; }

int mam
base *p;
//
base b_ob;
//
derived d_ob; //
//
//
= &b_ob;
p->setx(10); //
cout " : " p->getx() '\';
//
//
= &d_ob;
//
p->setx(99); //
//. . ,
//
d_ob.sety (88) ;
cout " : " p->getx ( ) ' ';
cout " : " d_ob,gety() '\'
return 0;

306

C++

, . , .

1. . , ,
, .

10.2.

(virtual function) . .
, , virtual. , , ,
. , "
, ", .

. , . , .
, virtual .
, -.
, .
, . ,
, ,
, ,
.
,
. , , , ,
. ,
, , ,

10,

307

, .
.
, , ,
(polymorphic class).

1. :
//
#include <iostream>
using namespace std;
class base {
public :
int i;
base {int x} { i = x; }
virtual void func()
{
cout " func() : ";
cout i '\n';

class derivedl : public base (


public :
derivedKint x) : base(x) ( }
void f unc ( )
{
cout " func() derivedl:
cout i * i '\n' ;
}

class derived2: public base {


public:
derived2 (int x) : base(x) { }
void f unc { }
{
cout " f unc ( ) derived2 : "
cout i + i '\n' ;

int main(}
{
base *p;

308

__

C++

base ob (10) ;
derivedl d_obl(10);
derived2 d_ob2(10);

p = sob;
p->func ( ) ; // f unc ( ) base
p = &d_obl;
p->func(); // func{) derivedl
p = &d_ob2;
p->func(); // f unc ( ) derived2
return 0;

:
func ( ) : 10
f unc ( ) derivedl: 100
func() derived2: 20


. . -,
/ ,
, ,
. ( ,
,
.)
, .
. , , . ,
(overriding).
. base
func(). : derivedl derived!.
func() -. main()
base, derivedl derived!.
ob ( base).
func () base. d_obl func()
. , ,
, derivedl. , d_ob2,
func(). func(),
derived!.

309

, , ,
, -, .
2. .
, ,
, . ,
:
//
#include <iostream>
using namespace std;
class base {

public:

*. i;

int

base (int x) { i = x; }
virtual void unc{)
{

cout " f u n c f ) : ";


cout i ' \ n ' ;

} /*

class derivedl: public base {


public:
derivedl (int x) : base(x) { }
void f unc ( )
{
cout " func() derivedl: ";
cout i * i *\n';

class derived2: public base {


public :
derived2(int x) : base(x) { }
// derived2 f unc ( )
}/

int rnainO
{
base *p;
base ob(10) ;
derivedl d_obl(10) ;
derived2 d_ob2(10);
p = sob;
p->func(); // func ( )

310

C++
= &d_obl;
p->func(); // func{) derivedl
= &d_ob2;
p->func{); // func()
return 0;

:
func() : 10
f unc ( ) derivedl: 100
f unc { ) : 10

derivedl func() .
d_ob2 func(),
base, . ,
, .
3. ,
.
d_obl d_ob2 ,
rand(). , func() .
(, ,
,
.)
/*
.
V
# include <iostream>
^include <cstdlib>
using namespace std;
class base {
public:
int i ;
base (int x} { i = x; }
virtual void func()
{
cout " func() : ";
cout i '\n' ;

class derivedl: public base {


public:
derivedl (int x) : base(x) { )

10.

311

void fume ( )
cout " func() derivedl: ";
cout i * i '\n';

class derived2: public base {


public:
derived2(int x) : b a s e ( x ) { }
void func ( )
cout " f u n c ( ) derived2: ";
cout i + i ' \ n ' ;

int m a i n ( )
base *p;
derivedl d_obl(10);
derived2 d_ob2(10);
int i, j;

for(i=0;
j = rand();
if ( ( j % 2 ) > p = &d_obl; //
//
else p = &d_ob2;
//
//
p->func {) ;
//


d_obl

d_ob2

return 0;

4. .
area,
.
getareaQ, , , , . getarea() .
, area.
.
//
^include <iostream>
using namespace std;

312

C++

class area {
double diml, dim2; //
public:
void setarea(double dl, double d2)
diml = dl;
dim2 = d2;
void getdim(double sdl, double &d2)
dl = diml;
d2 = dim2;
virtual double getareaO
cout " ";
return 0.0;

class rectangle: public area {


public:
double getareaO
double dl, d2;
getdim{dl, d2);
return dl * d2;

};
class triangle: public area {
public:
double getarea()
double dl, d2;
getdim(dl, d2);
return 0.5 * dl * d2;

int mainf)
(
area *p;
rectangle r;
triangle t;
r.setarea{3.3, 4.5)
t.setarea(4.0, 5.0)

10.

313

&;

cout " : " p->getarea() '\';


= fit;

cout " : " p->getarea() '\';


return 0;

, getarea() area
"" , , .
area , , getarea() area.
, , getarea() . .

num.
shownum().
outhex outoct, num.
shownum() ,
, .
2. , dist double . dist
trav_time(), ,
, , 60 .
metric trav_time() , , , ,
, 100 .

10.3.

4 , ,
, . ,
.
- ,
.

314

C++

, ,
, . C++
(pure virtual function).
.
.
:
virtual ^(_) = 0;

.
, . , ,
.
, . ,
, ,
.
,
(abstract class).
, , ,
, ,
. , . . , , -
, . (
.)
,
. ,
,
( , ). ,
f(), D1 , D2 D1,
f() D1, D2.

1. , 4 . area getarea()
.
//
^include <iostream>
using namespace std;

10.

class area (
double diml, dim2; //
public:
void setarea(double dl, double d2)
diml = dl;
dim2 = d2;
void getdim(double &dl, double &d2)
f
dl = diml;
d2 = dim2;
virtual double getareaO = 0; /V

class rectangle: public area {


public:
double getareaO
double dl, d2;
getdim(dl, d2);
return dl * d2;

)
};
class triangle: public area (
public:
double getareaO
{
double dl, d2; getdim (dl, d2);
return 0.5 * dl * d2;

int main{)
(
area *p;
rectangle r;
triangle t;
r. setarea (3.3, 4.5) ;
t. setarea (4.0, 5.0);

p = &r;
cout " : " p->getarea() '\n';

375

31f>

C++

p = &t;

cout " : " p->getarea() '\n';


return 0;
, getareaQ ,
.
2. , :
/*

*/
^include <iostreara>
using namespace std;
class base {
public:
virtual void func(}
{
cout " f unc { ) \";

class derivedl: public base {


public:
void f unc ( )
{
cout " func() derivedl \n";

// derivedl derived2
class derived2: public derivedl {
public:
void f unc ( )
{
cout " func() derived2\n";

int main ( }
I

base *p;
base ob;
derivedl d_obl;
derived2 d_ob2;

10.

317

= sob;
p->func(); // func()
= &d_obl;
p->func(); // func() derivedl
= &d_ob2;
p->func(); // func() derived2
return 0;

func()
derivedl, . derivedl
derived2. derived! funcQ .
,
derivedl funcQ , d_ob2
derivedl
func(). func() derivedl,
derivedl, func() base.

emiflj
'
1. . , area 1, . 2 funcQ derivedl. , func(), derivedl.
2. ?
3. 2 func()
derivedl? ? , ?

10.4.
, , , ,
. ,
,
( ) , . . " , ". ,

318

C++

.
,
, .
:
;
. , .
, - C++ .
(early binding) (late binding).
, . , .
, .
"" ,
, - .

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

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

, " , ".
. storeQ retrieve().
store(). -

10.

319

retrieve(). list . , " .


; .
, .
.
//
^include <iostream>
^include <cstdlib>
#include <cctype>
using namespace std;
class list (
public :
list *head;
list *tail;
list *next;
int num;

//
//
//
//

list () { head = tail = next = NULL; }


virtual void store (int i) = 0;
virtual int retrieve () = 0;

//
class queue: public list {
public:
void store (int i) ;
int retrieve ( ) ;
>;
void queue: : store (int i)
{
list *item;
item = new queue;
if (! item) {
cout " \
exit(l) ;
1
item->num = i;
//
if (tail) tail->next = item;
tail = item;
item->next = NULL;
i f ( ! h e a d ) head = tail;

320

__

int queue: : retrieve ()


)

int i;
list *p;
if {! head) {
cout " \";
return 0;

//
i = head->num;
= head;
head = head->next;
delete p;
return i;

//
class stack: public list {
public:
void store (int i);
int retrieve () ;

void stack: :store (int i)


list *item;
item = new stack;
if ( ! item) i
cout " \";
exit (1) ;
}
item->num = i;
//
if (head) item->next = head;
head = item;
if (Itail) tail = head;

int stack : : retrieve ( )


{
int i ;
list *p;
if (! head) {
cout " ";

C++

10.

321

return 0;

//
i = head->num;
= head;
head = head->next;
delete p;
return i;
}

int main()
{
list *p;
//
queue q_ob;
p = &q_ob; //
p->store(1);
p->store(2);
p->store(3);
coot
cout
cout
cout

": ";
p->retrieve();
p->retrieve();
p->retrieve();

cout '\nr;
//
stack s_ob;
p = Ss_ob; //
p->store(l);
p~>store{2);
p->store (3);
cout
cout
cout
cout

": ";
p->retrieve();
p->retrieve();
p->retrieve ();

cout '\n';
return 0;

2. main() . main():

322

C++

int main ()
{
list *p;
stack s_ob;
queue q_ob;
char ch;
int i;
for(i=0; i
cout " ? (/): ";
cin ch;
ch = tolower(ch);
if(ch=='o') p = &q_ob;
else p = ss_ob;
p->store (i) ;
cout " \";
for(;;) {
cout " 9 fr-/ry "
cin ch;
ch = tolower (ch) ;
if (ch=='Kp ) break;
if{ch=='o') p = &q_ob;
else p = &s_ob;

cout p->reteieve ( ) '\n';


}

cout '\n';
return 0;

main() , ,
, ,
. for 0 9.
. ,
( ),
. , .

.
, , ,
,
. , Windows . , -

10.

323

. .

]
1. 1.
( ) .
sorted.
2. , , .




.
1. ?
2. ?
3. ? .
4. ?
5. ? ?
6. ? , ?
class base {
public:
virtual int f(int a) = 0;

class derived: public base {


public:
int f (int a, int b)
( return a*b; }

7. ?
8. .
, .

324

C++



, .
1. , 1 4 ,
+ . +
, .
2. ?
3. . , . , ,
.

11

C++
: (templates) (exception handling). , C++,
Standard C++.

:
.
(generic functions)
(generic classes). , , . .
. ,
.
C++
, , . C++
. ,

, "" . .


,
.

326

C++

1. ?
2. ? , ?
3.

. ( .)
4. ( ) , ,
?
5. ?
?

11.1.
, .
, . . , ,
, . ,
,
. ,
.
.
,
.
, ,
.
template.
(. . ) C++.
( ), , ,
. -:
template <class > __ _(_)
{

II

.
.
, .

1 /.

327


class,
typename.

^_

1. ,
, . , .
//
^include <iostream>
using namespace std;
// -
template <class X> void swapargs(X &a, X &b)
{
X temp;
temp = a;
a = b;
b = temp;
I

int main()

{
int i = 10, j = 20;
float x = 10.1, = 23.3;
cout " i, j : " i ' ' j endl;
cout " x, : " x ' ' endl;
swapargs (i, j ) ;
swapargs (x, y) ;

//
//

cout " i, j : " i ' ' j endl;


cout " x, : " x ' ' endl;

return 0;
'

template .
:
template <class X> void swapargs(X &, X & b )

: -, , , -,
. X , .

328

C++

template swapargs() X
. mainO swapargs() : . swapargs() , : ,
. .
, C++. -, ( ,
template)
- (template function).
, ,
(generated function). (instantiating) . ,
-.
2. template
, . ,
swapargs():
template <class X>
void swapargs (X &a, X &b)
{
X temp;
temp = a;
a = b;
b = temp;

, template . , :
//
template <class X>
int i;
//
void swapargs (X &, X &)
{
X temp;
temp = ;
= b;
b = temp;

, template .

1.

329

3. ,
class
typename. ,
swapargsQ:
// typename
template <typename X> void swapargs (X &a, X Sb)
I
X temp;
temp = a;
a = b;
b = temp;

typename
,
,
4. template
, . , ,
:
#include <iostream>
using namespace std;
template <class typel, class type2>
void myfunc (typel x, type2 y)
cout x ' ' endl;
int m a i n ( )
{
myfunc (10, "hi") ;
myfunc(0.23, 10L) ;
return 0;
}


myfunc(), typel type2
int char* double long .

, ,
.

C++

330

5. ,
.
. ,
. ,
, .
void outdataCint i)
j
cout i;

void outdata(double d)
{

cout setprecision(lO) setfill ('#');


cout d;
cout setprecision(6) setfill (' ');
}

6. , - , .
, ( "")
, . 1:
// -
ttinclude <iostream>
using namespace std;
template <class X> void swapargs(X &a, X &b)
{
X temp;
temp = a;
a = b;
b = temp;
}

// swapargs()
void swapargs(int a, int b)
{
cout " swapargs(int, int)\n";
}
int main()
{
int i = 10, j = 20;

float x = , = 23.3;
cout " i, j : " i ' ' j endl;
cout " , : " x ' ' endl;

11.
swapargs(i, j ) ;
swapargs(, ) ;

337

// s w a p a r g s ( )
//

cout " i, j : " i ' ' j endl;


cout " , : " ' ' endl;
return 0;

, swapargs(i, j)
swapargs()
,
swapargs(),
.
, , ,
. ,
, .

]
1. , .
2. min(),
. , min(3, 4) 3, min('c', 'a') . .
3. - fmd().
.
( ), 1, .
flndQ.
find() .
( size .)
int find(int object, int *list, int size)

4. ,
.

332

__

C++

11.2.
.
, , , .
, . , , ,
. , ,
, .
, , . .
.
, .
:
template <class > class {

,
. , .

:
_ <> ;

, .
- .
template.
14, C++ , (Standard
Template Library, STL). .
"
, .

1. , . .

1 1.

333

//
# include <iostream>
using namespace std;
template <class data_t> class list {
data_t data;
list *next;
public:
list (data_t d) ;
void add (list *node) { node->next = this; next = 0; }
list *getnext() { return next; }
data_t getdataf) { return data; }
template <class data_t> list<data_t>: : list (data_t d)
i
data = d;
next = 0;
)
int m a i n ( )
{
list<char> start { 'a' ) ;
list<char> *p, *last;
int i;
//
last = sstart;
for(i=l; i<26; i++} {
p = new list<char> ('a1 + i) ;
p->add(last) ;
last = p;
}
//
p = Sstart;
while (p) {
cout p->getdata {) ;
p = p->getnext () ;
}
return 0;
, . , ,
. , ,
.
main (), , char. :
list<char> start ( ' a ' } ;

334

C++

, .
.
, .
, ,
, . , ,
:
list<int> int_start (1) ;

list
. , :
struct addr {
char name [40] ;
char street [40] ;
char city [30];
char state[3] ;
char zip[12] ;

, list addr,
(, structvar
addr):
list<addr> obj (structvar) ;

2. .
stack, 1.
stack . ,
.
:
//
^include <iostream>
using namespace std;
#define SIZE 10
// stack
template <class StackType> class stack {
StackType s t c k f S I Z E ] ;
//
int tos;
//
public:
void i n i t ( ) { tos = 0 ; } //
void push (StackType ch) ; //
StackType ( ) ;
//

1.

//
template <class StackType>
void stack<StackType>: :push(StackType ob)
{
if (toa SIZE) {
cout " ";
return;
}
stck[tos] = ob;

tos++;
//
template <class StackType>
StackType stack<StackType>: :pop ()
{
if (tos==0) {
cout " ";
return 0; //

tos ;
return stckftos] ;
int main ( )
<

//
stack<char> si, s2; //
int i ;
//

s2.init();
si.push ('a')
s2,push{'x')
si.push Cb')
s2.push('y1)
si.push{'c')
s2.push('z'}
for(i=0; i<3
for(i=0; i<3

i++) cout " 1:" sl.popO "\n


cout " 2:" s2.pop() "\n

// double
stack<double> dsl, ds2; //
//
dsl.init() ;
ds2.init() ;

335

336

C++

dsl.push(l.l)
ds2.push(2.2)
dsl.push{3.3)
ds2.push(4.4}
dsi.push(5.5)
ds2.push(6.6)
for(i=0; i<3; i++) cout " 1:" dsl.pop{) "\n
for(i=0; i<3; i++) cout " 2:" ds2.pop() "\n
return 0;

stack ( list),

,
, . ,
, .
- . template, . , :
//
^include <iostream>
using namespace std;
template <class Typel, class Type2> class myclass
Typel i;
Type2 j;
public:
myclass(Typel a, Type2 b) ( i = a; j = b; }
void show() { cout i ' ' j '\n'; }
i.
11
int main ()
myclass<int, double> obl(10, 0.23);
myclass<char, char *> ob2('X'f " ");
obl.showf);
ob2.show();

// int double
// char char *

:
10 0.23
X

11.

337

. obi
. 2 .
.

!
1. ^^*
, . /
.
2. , .
3. input, :
-,
,
-,
.
input :
input ob ("^" , _, _)

^ ~ , .
_ _ . ( , , ,
_ _.)

11.3.

C++ ,
(exception handling).
. C++ ; try, catch throw.
, , , try. (. . )
try, ( throw),
( catch) .
.

C++

335

, ,
, try. (, try .) catch,
try, . try
catch:
try {
//

catch (typel arg-) {


//
}
2
catch (type- arg) {
//
}
catch (type3 arg) {'
If

catch (typeW arg) {


//

try ,
. , inainO ( ).
,

catch, . try catch. To, catch ,
. , , catch, ,
catch. try (. . , -
try , catch,
try, . .). , arg .
, catch
type, arg .

11.

339

, . .
throw:
throw _!;

throw try,
, ( ).
^ throw .
, catch, .
Standard C++,
terminate(). terminate()
abort(), .
.

1. , C++
:
//
ttinclude <iostream>
using namespace std;
int mainO
cout " \n";
try {
// try
cout " try\n";
throw 10;
//
cout " "
}
catch (int i) { //
cout " : ";
cout i "\n";
cout "";
return 0;

340

C++

try
: 10

. , try, , catch (int i), . try


cout throw. , catch
try . , catch ,
. ( .) ,
throw cout .
catch, . , catch exit(), abort() - , , , , .
2. ,
, catch. , ,
catch double,
. :
//
^include <iostream>
using namespace std;
int main ( )
{
cout "\";
try {
// try
cout " try\n";
throw 10;
//
cout " ";
}
catch (double i) { //
//
cout " : ";
cout i "\n";
cout "";
return 0;

11.

341

catch double, :

try
Abnormal program termination

3. try
, , try- ,
:
/* ,
try
*/
ttinclude <iostream>
using namespace std;
void Xtest(int test)
t
cout " Xtest, test : " test "\n";
if (test) throw test;

int main()
I
cout "\";
try {
// try
cout " try\n";
Xtest (0);
Xtest (1);
Xtest (2);
catch (int i) { //
cout " : ";
cout i "\n";
cout "";
return 0;

try
Xtest, test :
Xtest, test : 1

__

342

C++

: 1

4. try . .
, :
^include <iostream>
using namespace std;
// try catch main ( )
void Xhandler (int test)
(
try f
if (test) throw test;
}
catch(int i) {
cout " : " i ' \n ' ;

int main ( }
{
cout "";
Xhandler (1) ;
Xhandler (2} ;
Xhandler (0) ;
Xhandler (3) ;
cout "";
return 0;

: 1
: 2
: 3

, . . .
5. , try
catch. , . catch -

11.

343

. ,
,
:
tinclude <iostream>
using namespace std;

//
void Xhandler(int test}
try

{
i f ( t e s t ) throw test;
else throw " ";

catch (int i} {

cout " : " i '\n';


catch(char *str) (
cout " : ";
cout str p \ n ' ;

int main ()
{
cout "\";
Xhandler(l);
Xhandler(2);
Xhandler(O);
Xhandler(3);
cout "";
return 0;

: 1
: 2
:
: 3

, catch
.
catch ,
. ,

344

C++

. catch .

[
]
1. , C++ . ,
.
, .
2. ?
int main ()
{
throw 12.23;

3. ?
try

// . ..

throw ' ' ;

catch (char *) {

4. ,
catch?

11.4.

, .
, , . . catch:
catch (...) {
//

1.

345

.
, try,
, .

.
throw.
:
&_ _ (_>)

throw ( _ )

_
, .
. ,
, _
.

Standard C++,
unexpected().
unexpectedQ abort(),
.
. .
,
throw . , try/catch.

1. catch(...):
//
^include <iostream>
using namespace std;
void Xhandler(int test)
try {
// int
if(test==0) throw test;

346

C++
// char
if(test==l) throw 'a';
// double
if (test2) throw 123.23;
}
catch (...) { //
cout " !\";

}
int main ()
cout "\";
Xhandler(O);
Xhandler(l);
Xhandler(2);
cout " "
return 0;

!
!
!

,
throw, catch.
2. catch(...)
catch. catch(...)
, " ". , , , catch(...):
/* catch (...)

*/
^include <io5tream>
using namespace std;

void Xhandler(int test)

1.

347

t {

// int
if(test=0) throw test;
// char
if (test 1} throw 'a';
// double
if (test 2) throw 123.23;

}
catch(int i) { // int
cout " " i '\n';
}
catch (...) { //
cout " ! \" ;

int main {)
{
cout "\ " ;
Xhandler(O) ;
Xhandler(l) ;
Xhandler(2) ;
cout "";
return 0;


!
!

, catch(...)
,
. ,
- .
3. , , :
/*

*/

ttinclude <iostreara>
using namespace std;

348

C++

II
// int, char double
void Xhandler (int test) throw(int, char, double)

{
// int
if (test0) throw test;
// char
if(test=l) throw r a r ;
// double
ifttest 2) throw 123.23;

int main ()
(
cout "\";

try {
Xhandler(O); //
// Xhandler () 1 2
catch (int i) {
cout " int\n";

J
catch (char c) j
cout " char\n";
}
catch (double d) {
cout " double\n" ;
}
cout "" ;
return 0;

Xhandler() int, char double. . ( unexpected<>.) ,


int
.
, , try- To
try , .
, .

1.

349

4. Xhandler() :
//
void Xhandler (int test) throw ( )
/* . ,

*/

// int
if (test==0) throw test;
// char
if(test==l) throw 'a';
// double
if(test=2J throw 123.23;

, .
, . , , , .
catch ( ,
). ,
catch, , . :
char *.
/*

*/
^include <iostream>
using namespace std;
void Xhandler ()
{
try {
// char *
throw "";
j
// char *
catch (char *) {
cout " char * Xhandler () \n";
/ /
// char *, Xhandler ()
throw;

C++

350
int

main()

cout "";

try {
XhandlerO ;
}
catch(char *) {
cout " char * main()\n";
}

cout "";
return 0;

char * XhandlerO
char * main()

\. ,
. , ,
.
2. ?
try

// ...

throw 10;

}
catch (int *p) {

3. .
4. catch ?
5. dividcQ
double divide (double a, double b)
{
//
return a/b;

11.

35?

. , . , .

11.5.

,
new
v

4 , new, . 4 , , .
new.
new , Standard C++.
4, C++
, new, .

new ,
. ,
. , new
,
. , new - .
Standard C++, .
,
,
new.
Standard C++,
, new bad_alloc. .
,
, - . <new>.

352

C++

xalloc

. , ,
Standard C++ bad_alloc.
, Standard
C++ , new , .
new ,
malloc() new.
new:
= new(nothrow)

TIOI;

.
new nothrow ( )
, .
,
new ""

. ,
.

I. new
try/catch .
^include <iostream>
tfinclude <new>
using namespace std;
int main()
{
int *p;

{
p = new int; //
} catch (taad_alloc xa) {
cout " \";

try

1.

353

return 1;

for(*p = 0; * < 10; (*}-


cout * " ";
delete p; //
return 0;

, , catch.
2.
,

new . ,
.
^include <iostream>
^include <new>
using namespace std;

int raainO
,
double *p;
//

do {
try {
p = new double [100000];
} catch (bad_alloc xa) (
cout " \";
return 1;
}
cout " \";
} while (p) ;

return 0;

3, ,
new new(nothrow). .
// new(nothrow)
^include <iostream>
^include <new>

C++

354

using namespace std;


int main()
{
double *p;
//

do {

= new(nothrow) double[100000];
i f ( p ) cout " \";
else cout " \";
} while();
return 0;
}

, new nothrow,
.

1. , new
new(nothrow), .
2. .
C++.
= malloc(sizeof(int));
ifUp) {
cout " \";
exit(l);




.
1. , ,
.

11.

355

2. ,
.
3. "" (
).
4. stack , .
5. try, catch throw.
.
6. stack , , ,
.
7. , , terminate() unexpected(). ,
, . ,
,
.
8. : , ,

new ?



, .
1. 6, 6.7, 3 . .
2. 1 abs(). , abs(),
.

12


C++:
(Run-Time Type Identification, RTTI)
, (casting operators).
.
, .
, ,
dynamic_cast, RTTI,
.

,
.
1. ?
2. ?
3. gexpQ,
, .
4. 9, 9.7, 1 coord . ,
. .
5. , try, catch throw
C++ .
6. throw, , try?
7. terminate!) unexpectedQ?
8. catch ?

358

C++

12.1.


, (,
), . ,
, , ( ,
). , ,
(, C++), ,
,
. , C++
, . ,
, . ,
, .
,
.
lypeid.
typeid
<typemfo>. typeid:
typeid()

,
. typeid type_info, . type_info :
bool operator= (const type_info ) ;
bool operator!=(const type_info &);
bool before(const type_info ^);
const char *name();

== !=. before() , , . (
.
.) ()
.

12.

359

typeid ,
, .
, .
, ,
. (,
, , .) , typeid
,
. .
typeid , ,
. , ,
. typeid , .
typeid, :
typeid (_)

typeid
type_info, .
typeid (. . , *), , ,
bad_typeid,
typeid.
. , ,
.

typeid.

C++ int. typeid
, , BaseClass.
// typeid
#include <iostream>
^include <typeinfo>
using namespace std;

360

__

C++

class BaseClass {
virtual void f() (}; // BaseClass

class Derivedl: public BaseClass {

class Derived2 : public BaseClass {

int main ( )
i
int i;
BaseClass *p, baaeob;
Derivedl obi;
Derived2 ob2;
//
cout " i ";
cout typeid(i) .name () endl;
-

//
= Sbaseob;

cout " ";


cout typeid (*p) .name () endl;
= &obl;
cout " ";
cout typeid (*p) .name {) endl;.
= &ob2;

cout " ";


cout typeid{*p) .name (} endl;
return 0;

:
i int
BaseClass
Derivedl
Derived2
, typeid , , ,
. -

12.

361

f()
BaseClass , .
2. , typeid ,
, . , . , WhatType()
BaseClass -. , What() BaseClass , BaseClass. typeid ,
.
// typeid
^include <iostream>
^include <typeinfo>
using namespace std;
class BaseClass {
virtual void f()

{}; // BaseClass

class Derivedl: public BaseClass {

class Derived2: public BaseClass {

//
void WhatType (BaseClass &ob)
{
cout "ob ";
cout typeid(ob) ,name{) endl;
int main()

int i;
BaseClass baseob;
Derivedl obi ;
Derived2 ob2;
WhatType (baseob)
WhatType (obi)
WhatType (ob2)

362

C++

:
ob BaseClass
ob Derived!
ob Derived2

3.
, ,
. ,
type_info, typeid, == ! ,
.
// == != typeid
^include <iostream>
^include <typeinfo>
using namespace std;
class X {
virtual void f() {}
class Y {
virtual void f () { }
int main()
{
X xl, x2;

Y yl;
if (typeid(xl) == (typeid(x2))
cout " xl 2 ";
else
cout " xl 2 \";
if (typeid(xl) != ( typeid (yl))
cout " xl yl \";
else
cout " xl yl \";
return 0;

:
xl 2
xl yl

4.
type_info, , . -

12.

363

.
,
.
Shape. : Line, Square, Rectangle NulIShape
generator() .
(, ,
.) , , rand(). main{) , NulIShape,
.
, , . , .
// != typeid
#include <iostream>
tinclude <cstdlib>
#include <typeinfo>
using namespace std;
class Shape (
public:
virtual void example(} = 0;

class Rectangle: public Shape {


public:
void example (} {
cout "*****\ n *
*\n*

*\ n *****\ n ;

class Triangle: public Shape {


public:
void example ( } {
cout "*\n* *\n* *\n*****\n;

class Line: public Shape (


public:
void example () {
cout "*****\n";

class NulIShape: public Shape {


public:

364

void example () {

I
// Shape
Shape *generator{)
switch(rand(} % 4) {
.

case 0:

return
case 1 ;
return
case 2;
return
case 3:
return

new Line;
new Rectangle;
new Triangle/new NullShape;

1
return NULL;

int main ( )
{
int i;
Shape *p;
for(i=0; i
p =* generator (}; //
cout typeid(*p) .name () endl;
// , NullShape
if (typeid(*p) != typeid (NullShape) )
p->example () ;

}
return 0;

:
class Rectangle

class NullShape
class Triangle

C++

12.

365

class Line
*****
class Rectangle

class Line
*****
class Triangle

*****
class Triangle

*****
class Triangle

class Line

5. typeid -. , . -. get_val()
. Num . Square .
Sqr_root . ,
Num, genegator(). typeid .
// typeid
^include <iostream>
linclude <cstdlib>
ttinclude <cmath
#include <typeinfo>

using namespace std;


template <class T> class Num {
public:
;
Num(T i) { x = i; }

366

virtual get_val() { return x; }

};
template <class T>
class Squary: public Num<T> {
public:
Squary (T 1} : Num<T>(i) {}
get_val() { return x*x; }

template <class T>


class Sqr_root: public Num<T> {
public:
Sqr_root(T i): Num<T>(i) {}
get_val() { return sqrt ( (double) x) ; }
);
// Num
Num<double> * generator {)
(
switch {rand () % 2) {
case 0: return new Squary<double> (rand{) % 100);
case 1: return new Sqr_root<double> (rand() % 100);
}
return NULL;
int main()
{
Num<double> obi (10), *pl;
Squary<double> ob2(100.0);
Sqr_root<double> ob3{999.2);
int i;
cout typeid (obi) .name () endl;
cout typeid (ob2) .name () endl;
cout typeid (ob3) .name () endl;
if (typeid(ob2) == typeid (Squary<double>) )
cout "is Squary<double>\n";

pi = fiob2;
if (typeid{*pl) != typeid(obl))
cout " : " pl->get__val (} ;
cout "\n\n";
cout " \";
for(i=0; i<10; i++) {
pi = generator{); //

C++

12.

367

if(typeid(*pl) == typeid CSquary<double>))


cout " : ";
if (typeid(*pl) == typeid(Sqr__root<double>) )
cout " : ";
cout " : " pl->get_val()
cout endl;
return 0;

:
class Num<double>
class Squary<double>
class Sqr_root<double>
is Squary<double>

: 10000

: :
: : 0
: :
: : 3364
: : 4096
: :
: :
: :
: :
: :

8. 18535
^1. 89898

6. 7082
5. 19616
9. 53939
6. 43074

1. ?
2. , 1.
?
3. ?
cout t y p e i d ( f l o a t ) . n a m e ( ) ;

4. . , D2?
class {

virtual void f(} {}

C++

368

'

class Dl: public (


void f () {}

class D2: public {


void f ( > { }
i.

int rnainO
*;

5. 5
?
typeid(Num<int>) == typeid(Num<double>)
6. RTTI.

, .

12.2. dynamicjcast
C++ , . dynamic_cast, const_cast, reinterpret_cast static_cast.
dynamic_cast , . .
dynamic_cast ,

. dynamic_cast
, .
dynamic_cast:
dynamic < > ()

_ , .
. ,
dynamic_cast
.
dynamic_cast
. , -

12. ^

369

D, D ,
dynamic_cast D*
*. ,
. dynamic_cast * D*,
, , , D. , dynamic__cast , ( )
( ) ,
.
. dynamic_cast , . ,
bad_cast.
. , Base ,
a Derived , Base.
Base *bp, b_ob;
Derived *dp, d_ob;
bp = &d_ob; //
//
dp = dynamic_cast<Derived *> (bp)
if(!dp) cout " ";

bp dp
, bp Derived. ,

. , bp Base,
.
bp = Sb_ob; //
//
dp = dynamic_cast<Derived *> (bp)
if{!dp) cout " ";

,
.
dynamic_cast
typeid. , , Base
, a Derived , Base.
dp ,
bp, ,
Derived.

370

C++

Base *bp;
Derived *dp;
// ...
if(typeid(*bp) == typeid(Derived)) dp = (Derived *) bp;

. , if
typeid
, .
. typeid if dynamic cast:
f

dp = dynamic_cast<Derived *> (bp)

dynamic^cast , , , ,
, dp , Derived.
, dynamic_cast , , .

1. dynamic_cast:
// dynamic_cast
^include <iostream>
using namespace std;
class Base {
public:
virtual void f ( ) { cout " Base"\n; }
class Derived: public Base {
public:
void f ( ) { cout " Derived"\n; }
};
int

main{)
Base *bp, b_ob;
Derived *dp, d ob;

12.

371

dp = dynamic_cast<Derived *> (&d_ob);


if(dp) {
cout " Derived * Derived * \";

dp->f ;
} else
cout "\";
cout endl;
bp = dynamic__cast<Base *> (&d_ob);
if(bp) {
cout " Derived * Base * \";
bp->f();
} else
cout "\n";
cout endl;
bp = dynamic_cast<Base *> (&b_ob);
if(bp) {
cout " Base * Base * \";
bp->f();
} else
cout "\";
cout endl;
dp = dynamic_cast<Derived *> (sb_ob);
if (dp) {
cout "\";
} else
cout " Base * Derived * \";
cout endl;
bp = &d_ob; // bp Derived
dp = dynamic cast<Derived *> (bp);
if(dp) {
cout " bp Derived * \"
" \"
" Derived\n";
dp->f();
} else
cout "";
cout endl;
bp = &b_ob; // bp Base
dp = dynamic_cast<Derived *> (bp);
if(dp)
cout "\";

372

C++

else {
cout " Derived * \"
" \"
" \" ;

cout endl;
dp = &d_ob; // dp Derived
bp = dynamic_cast<Base *> (dp) ;
if(bp) {

cout " dp Base * \"


bp->f ( } ;
) else
cout " \n";
return 0;
:
Derived * Derived *
Derived
Derived * *
Derived

Base * Derived *
Derived *

Derived
Derived
Derived *


dp Base *
Derived

2. , typeid dynamic_cast.
/* dynaraic_cast typeid
*/
^include <iostream>

12.
^include <typeinfo>
using namespace std;
class Base {
public:
virtual void f() (}
};
class Derived: public Base {
public:
void derivedOnly() {
cout " Derived"\n;

int main()
Base *bp, b_ob;
Derived *dp, d_ob;

// typeid
bp = &b_ob;
if(typeid(*bp) = typeid(Derived)) {
dp = (Derived *) bp;
dp->derivedOnly();
} else
cout " Base Derived \";
bp - &d_ob;
if(typeid(*bp) == typeid(Derived)} {
dp = (Derived *) bp;
dp->derivedOnly();
} else
cout ", !\";

// dynamic_cast
bp = Sb_ob;

dp = dynarnic_cast<Derived *> (bp) ;


i f ( d p ) dp->derivedOnly(};
else
cout " Base Derived \";
bp = sd_ob;
dp = dynamic_cast<Derived *> (bp);

373

374

i f ( d p ) dp->derivedOnly{);
else
cout ", !\";
return 0;

, dynamic_cast .
:

Base

Base

Derived
Derived
Derived
Derived

3. dynamic_cast, typeid, -. , - 5 12.1. ,


genegator(), dynamic_cast.
// dynamic_cast
^include <iostream>
^include <cstdlib>
^include <cmath>
#include <typeinfo>
using namespace std;
template <class T> class Num {
public:
x;
Num(T i) { x = i; }
virtual get_val() { return x; }
template <class T>
class Squary: public Num<T> {
public:
Squary(T i): Num<T>(i) {}
get_val() { return x*x; }
1;
template <class T>
class Sqr_root: public Num<T> {
public:
Sqr_root(T i ) : Num<T>{i} ( }
get_val(} { return sqrt((double) x}; }

12.

375

// Num
Num<double> *generator()
switch(rand() % 2) {

case 0: return new Squary<double> (randf) % 100);


case 1: return new Sqr_root<double> (rand() % 100};
return NULL;
int

main()
Num<double> obl(lO), *pl;
Squary<double> ob2 (100.0), *p2;
Sqr_root<double> ob3(999.2), *p3;
int i;
cout " \";
for(i=0; i<10; i++) {
pi = generator ( } ;
p2 = dynamic_cast<Squary<double> *> (pi);
if(p2) cout " : ";
= dynamic_cast<Sqr_root<double> *> (pi);
if(p3) cout " :
cout " : " pl->get_val {)
cout endl;

}
return 0;

1. dynamic_cast.
2. . ,
dynamic_cast , ob
, ob D2.
class {
virtual void f ( ) {}
};

class Dl: public {


void f ( } { }

};

C++

376
class D2 : public {
void f { ) {}

3. main() 12.1, 4 ,
NuMShape typeid, dynamic_cast.
4. Num 3 ?
Num<int> *;
Square<double> *Dp;
Dp = dynamic cast<Num<int (Bp) ;

12.3. const_cast,
reinterpret_cast staticjcast
dynamic_cast
, . :
1:_<_> ()
_

()

static_cast<4&neBa#__!TJim> ()
_ , . ,

, , .
const_cast const () / volatile
(). , const volatile. const_cast const.
static_cast
. ,
. ,

12.

377

, (. . ).
reinterpret_cast
.
. reinterpret_cast
.
const
const_cast. dynamic_cast, static_cast reinterpret_cast
.

>^
1.
reinterpret_cast.

// reinterpret_cast
ttinclude <iostream>
using namespace std;
int
{

main{)
int i ;

char *p = " ";


//
i = reinterpret_cast<int> (p} ;
cout i;
return 0;

reinterpret_cast . reinterpret_cast.
2. const_cast
// const_cast
#include <iostream>
using namespace std;
void f (const int *p)
{
int *v;

378

C++
11 const
v = const_cast<int *> ();
*v = 100; // v
I

int main()
{
int x = 99;
cout " : " endl;
f(&x);
cout " : " endl;
return 0;

:
: 99
: 100

, f()
,
.

constjcast const
.
.

3. static_cast, , .
. ,
float int.
// static__cast
^include <iostream>
using namespace std;
int main(}
{
int i;
float f;
f = 199.22;

i = static cast<int> ( f } j

12.

379

cout i;
return 0;

1. , const_cast, reinterpret_cast static^cast.


2. . const_cast.
#include <iostream>
using namespace std;
void f (const double & i )
{
i = 100; // ! const_cast
I

int
{

main()
double x = 98.6;
cout x endl;
f (x);
cout x endl;
return 0;

3. , const_cast
.




.
1. ,
typeid.
2.
typeid?

C++

380

3. , C++ . ?
4. , .
^include <iostream>
#include <typeinfo>
using namespace std;
class A {
virtual void f(}

{}

class B: public A {
class C: public {
int main{)
A *p, a_ob;
b_ob;
c_ob;
int i;

cout " ,";


cout "1 ";
cout "2 .\";
cin i;

if (i-=l> p = &b_ob;
else if (i==2) p = Sc_ob;
else p = &a__ob;
//
//
return 0;

5. , typeid dynamic_cast
6. typeid?

12.

35?



, .
1. 12.1, 4,
generator() .
2. generator() 1,
new nothrow.
3. : DataStruct . . ,
. DataStructFactoryQ :
DataStruct *DataStructFactory(char );

DataStructFactoryO , s, , q. . ,
" " .

13

(namespaces),
(conversion functions), (static)
(const) , C++.

,
.
1.
?
2. typejnfo?
3. ?
4. . , , : Base
Derived.
class Base {
virtual void f ( )

{}

class Derived: public Base (


}t
int main()
Base *p, b_ob;
Derived d ob;

5. dynamic_cast ,
, ,

384

,
. ( .)
6. dynamic_cast const?

13.1.
1, . C++
. (name collisions). C++ , .

. ,
toupperQ, ( ) (oupperO,
. ,
.
, , , ,
.

namespace. , .

. ,
C++ (C++ standard
library). C++ . C++ std, .
, , , , .
.
namespace
. , .
namespace:
namespace {
I/

13.

355

, namespace, .
MyNameSpace:
namespace MyNameSpace {
int i, k;
void myfunc(int j) { cout j; }
class myclass {
public:
void seti(int x) { i = x; }
int geti{) { return i; }

i k, myfunc(), myclass
, MyNameSpace.
, , . ,
MyNameSpace return i i . namespace , ,
,
. , 10 i
, MyNameSpace,
:
MyNameSpace::i = 10;

myclass ,
MyNameSpace, :
MyNameSpace:imyclass ob;

,
.
,
,
.
using. :
using namespace ;
using ; .-;

386

C++

, .
using , ,
,
. using . , MyNameSpace, using :
using MyNameSpace::k; // k
k = 10; // , k
using namespace MyNameSpace; //
// MyNameSpace
i = 10; // ,
// MyNameSpace


.
. :
namespace NS {
int i;

namespace NS {
int j ;

NS . , - NS.
, .
, . , , ,
.

(unnamed namespace).
, . :

13.

357

namespace {

//


, . , ,
, , . .

. , , , , .

1. .
//
#include <iostream>
using namespace std;
//
namespace firstNS {
class demo (
int i;
public:
demo(int x) ( i = x; }
void seti(int x) { i = x; }
int geti() { return i; J
char str[] = " \
int counter;

)
//
namespace secondNS {
int x, ;
}
int

main{}

388

C++

I/
firstNS::demo ob(10);
/* ob, -
,

*/
cout " ob : " ob.geti();
cout endl;
ob.seti(99);
cout " ob : " ob.getif);
cout endl;
// str
using firstNS::str;
cout str;
// firstNS
//
using namespace firstNS;
for(counter=10; counter; counter)
cout counter " ";
cout endl;
// secondNS
secondNS::x = 10;
secondNS::y = 20;
cout " x, : " secondNS::x;
cout ", " secondNS::y endl;
// secondNS
//
using namespace secondNS;
demo xob{x), yob(y);

cout " xob, yob : " xob.geti()

cout ", " yob.getiU endl;


return 0;

:
ob : 10
ob : 99

10 9 8 7 6 5 4 3 2 1
, : 10, 20
xob, yob : 10, 20

3.

359

:
.
, , ,
.
,
std, firstNS secondNs.
2. , , ,
.
.
//
^include <iostreara>
using namespace std;
namespace Demo {

int a; // Demo
int x; //
namespace Demo {
int b; // Demo

'

int rnain{)
/
using namespace Demo;
a = b = x = 100;
cout a " " b " " x;
return 0;

, b,
Demo,
.
3. , Standard C++
std.
:
using namespace std;

std , , Standard C++,

++

390

,
std.
, ,
std . , Standard C++ .
//
^include <iostream>
int main ()
double val;

std::cout " : ";


std; :cin val;

std::cout " : ";


std::cout val;
return 0;

,
cin cout,
.
Standard C++, std
. ,
,
std ,
.
4. , using . ,
, . :
//
^include <iostream>
// cin cout
using std::cout;
using std: :cin;
int
{

main()
double val;

13.

391

cout " : ";

cin val;
cout " : ";
cout val;
return 0;

cin cout
, std .
5. , C++ .
C++, using namespace std,
std::. ,
( -h). ,

, std.
6. ,
, ,
, . . static. , ,
:

static int counter;
void fl() {
counter = 99; // OK


extern int counter;
void f 2 ( ) {
counter =10; //

counter ,
. , counter extern,
.
counter , .
static C++
- ,
, , .

namespace {
int counter;
1
void f l ( ) {
counter = 99; // OK


extern int counter;
void f 2 ( )

counter = 10; //

392

C++

counter .
static Standard C++.

I. 9 ,
using namespace std.
// |
ftinclude <iostream>
^include <fstream>
using namespace std;
int main{int argc, char *argv[])
(

if(argc!=3) {
cout " < > < >\";
return 1;
ifstrearn fin (argvfl]); //
ofstreara fout(argv[2]); //
if{!fout} {
cout " \";
return 1;
}
if(!fin) {
cout " \";
return 1;
}

char ch;
fin.unsetf(ios::skipws); //
while{!fin.eof{)) {
fin ch;
if(ch==' ') ch = '|';
if (!fin.eof()) fout ch;
fin.close();
fout.close();
return 0;
}

13.

393

2. .
3. using.
4. ,
using. .
5. , , .

13.2.

. , ( )
. (conversion
function) , , C++.
, , , .
:
operator () { return ; }

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

coord ,
.
; .
//
ttinclude <iostream>
using namespace std;

394

__

C++

class coord {
int x, ;
public:
coord{int i, int j) { x = i; = j; }
operator int{) { return x*y; } //
int main()
coord ol(2, 3), o2(4, 3) ;
int i;
i = ol; // ol
cout i '\n';
i = 100 4 o2; // 2
cout i '\n';
return 0;

6 112.
, ,
ol , 2 ,
, . ,
"" , - .
2. .
strtype str.
ttinclude <iostream>
^include <cstring>
using namespace std;
class strtype {
char str[80] ;
int len;
public:

strtype [char *s) { strcpy(str, s); len = strlen(s); }


operator char *() { return str; } // char *
int main()
{
strtype {" \n" };
char *p, s 2 [ 8 0 J ;

13.

_ 395_

= s; // char *
cout " : " ' \ ' ;
// char *
strcpy{s2, s) ;
cout " : " s2 ' \ n ' ;
-

return 0;

:
:
:
,
s ( char *),
strcpy(). ,
strcpyO :
char *strcpy(char *sl, const char *s2) ;

, s2 char *,
char * .
,
C++.

)
1. strtype 2,
.
, str. , .
2. :
class pwr (
int base;
int exp;
public:

pwr{int b, int e) { base = b; exp = e; }


//
3. pwr . baseexp.

396

C++

13.3.
(static). -, . , ,
.
( ) . , - ,
. ( , .) , , . ,
, ,
.
, , . , ,
, . ,
, -
.
- , . - .
, ,
(redeclare) ,
.
- . , ,
.
, C++ - , . ,
, ,
OOP C++.
- , .

. (, .)
- this. . -

13.

397

const () volatile (). ,


,
.

""^igj^

1. -.
// -
ttinclude <iostream>
using namespace std;
class myclass {
static int i;
public:
void seti(int n) { i = n; }
int geti(} { return i; }

// myclass: :i. i -
// myclass
int myclass : :i;
int main()
{
myclass ol, o2;
ol.seti(lO);
cout "ol.i: " ol.getiO T\n'; // 10
cout "o2.i: " o2.geti() '\np; // 10
return 0;

:
ol.i:
o2.i:

10
10

, , ol
- i. i ol 2 (, , myclass), geti()
.

398

C++

, i myclass,
. , i . , . . - ,
2. ,
. , i 100 .
i.
//
tfinclude <iostream>
using namespace std;
class myclass {
public:
static int i;
void seti{int n) { i = n; }
int g e t i ( ) { return i; }
int myclass::i;
int main ()
myclass ol, o2;
// i
myclass::! = 100; //
cout "ol.i: " ol.geti() '\n'; // 100
cout "o2.i: " o2.geti{) '\n'; // 100
return 0;

i 100, :
ol.i: 100
o 2 . i : 100

3.
, ,
. , , ,

13. _

399

. , - , . output, outbnf,
. ,
- outbuf().
str. , str.
.
.
//
ttinclude <iostream>
^include <cstring>
using namespace std;
class output {
static char outbuf[255]; //
static int inuse; // inuse ,
// ;
static int oindex; //
char atr[80];
int i; //
int who; //
public:
output(int w, char *s) {
strcpy(str r s); i = 0; who = w;
}
/* -1 ; 0
; who .
*/
int putbuf()
{
if(!str[i]) { //
inuse =0; //
return 0; //

}
if (!inuse) inuse = who; //
if(inuse != who) return -1; // -
if(str[i]) { //
outbuf[oindex] = str[i];
i++; oindex++;
outbuf[oindex] = '\0'; //
return 1;
return 0;

400

C++
void show() { cout outbuf '\n';}
};

char output::outbuf[255]; //
int output::inuse = 0; // inuse ,
// ;
int output::oindex = 0; //
int main()
{
output ol(l,

" " ) , 2{2,

" ");

while (ol.putbuf{) I o 2 . p u t b u f ( ) ) ; //
ol.show() ;
return 0;

4. - , ( ) - . , .
^include <iostream>
using namespace std;
class static__func_demo {
static int i;
public:
static void init(int x) { i = x; J
void show() { cout i; }

};
int static_func_demo::i; // i
int main()
(
//
static_func_demo::init(100);
static_func_demo x;
x.show{); // 100
return 0;

init() i
static func demo.

13.

40 J

]
1. 3 , ,
, , .
2. -
, .
- , , , . .

13.4.

( const). ,
. ,
-. , - , .
- , :
class X {
int some_var;
public:
int fl() const; // -

, const
, .
, , -,
,
.
( mutable).
-.

1. - ,
.
.

402

C++

/* -.

*/
#include <iostream>
using namespace std;
class Demo {
int i;
public:
int geti () const (
return i; //
}
void seti{int x) const {
i = x; // ! ! !

int main ( )
Demo ob;
ob.seti(1900) ;
cout ob.getif);
return 0;
, - seti()
,
. , i . , geti() i, .
2. , . .
//
#include <iostream>
using namespace std;
class Demo {
mutable int i;
int j ;
public:
int geti() const {
return i; //
}

void seti(int x) const {


i = x; //

13.

403

/* ,

void setj (int x) const {
j = x; //
}
*/
int main ()
{
Demo ob;
ob.seti(1900) ;
cout ob.geti () ;
return 0;
I

i ,
- seti(). , ] - , - seti() .

!
_^
. . , ,
, . .
//
#include <iostream>
using namespace std;
class CountDown {
int incr;
int target;
int current;
public:
CountDown(int delay, int i ~ 1)
target = delay;
incr = i;
current = 0;
}
bool counting{) const {
current += incr;

404

C++
if(current >= target) {
cout " \ a " ;
return false;
}
cout current " ";
return true;

int main{)
{
CountDown ob(100, 2);
while(ob.counting());
return 0;

2. - ?
, ?

13.5.

,
. :
^include <iostream>
using namespace std;
class myclass {
int a;
public:
myclass(int x) { a = x; }
int geta() { return a; )
int main{)
myclass ob(4);
cout ob.geta(};

return 0;

13.

405

myclass . , main ob. 4,


ob, , myclassQ .
, .
. , ,
:
myclass ob = 4; //
// myclass ob{4);

,
myclassQ 4 . , , :
myclass o b ( 4 ) ;

, , ,
. , , .
explicit (). explicit .
, explicit,
. . ,
myclass explicit, . myclass()
explicit.
^include <iostream>
using namespace std;
class myclass {
int a;
public:
explicit myclass (int x) { a = x; }
int geta() { return a; }

:
myclass o b ( 4 ) ;

406

C++

1. . ,
myclass.
#include <iostream>
#include <cstdlit>>
using namespace std;

class myclass {
int a;
public:
myclass (int x) { a = x; }
myclass (char *str) { a = atoi(str); }
int geta() { return a; }
i

int main()
{
// myclass ob{4)
myclass obi = 4;
// myclass ob("123"3
myclass ob2 = "123";
cout "obi: " obl.getaO endl;
cout "ob2: " ob2.geta{) endl;
return 0;

( )
.
2. . ,
myclass 1, 2
, main() int
char *.
linclude <iostream>
^include <cstdlib>
using namespace std;
class myclass {
int a;
public:
myclass (int x) { a = x; }

myclass (char *str) { a = a t o i ( s t r ) ; }

13.
int g e t a ( )

407

{ return a; }

};

int main(}
{
// myclass o b ( 4 )
myclass obi = 4;

// myclass ob("123")
myclass ob2 = "123";
cout "obi: " obl.getaO endl;
cout "ob2: " ob2.geta{) endl;
/*

*/
// myclass ob("1776")
myclass obi = "1776";
// myclass ob(2001)
myclass obi = 2001;
cout ": " obl.getaO endl;
cout "ob2: " ob2.geta(} endl;
return 0;

3. ,
explicit:
^include <iostream>
ftinclude <cstdlib>
using namespace std;
class myclass (
int a;
public:
explicit myclass(int x) { a = x; }
.
explicit myclass(char *str) { a = atoi(str); }
int geta() { return a; }

int mainO
{
// myclass ob(4)
myclass obi = 4;
.
// myclass ob{"123"}
myclass obi - "123";

408

C++
cout "obi: " o b l . g e t a O endl;
cout "ob2: " ob2.geta() endl;
return 0;

'
]
1. 3 f explicit
myclass(int),
myclass(char *)? (: , .)
2. ?
class Demo {
double x;
public:
Demo{double i) ( x = i; }

Demo counter = 10;


3. explicit. ( ,
, .)

13.6.
asm
C++ C++
.
(linkage specifier), , C++ , . .
asm, . .
C++ C++. C++ ,
,

g.

409

. C++
, C++.
, Pascal, Ada FORTRAN.
, :
extern "" ;

,
. ,
:
ex-tern "" {
;

;
.
C++
. "" (mangling)
. C++ -,
.
, ,
-, ,
.
"" .

C++, C++. C++ asm, C++. ,
C++,
, . asm:
asm <"_");

_ ,
.
,
, asm:
asm _;
asm

410

C++

asm {

.

.

S Microsoft Visual C++


asm. So asm.

1. func() C++,
:
//
ttinclude <iostream>
using namespace std;
extern "C" int func(int x ) ; //
// .
int func(int x)
(
return x/3;

, .
2. ,
(), () f3() :
extern "" {
void f 1 ( ) ;
int f 2 ( i n t x ) ;
double f3 {double x, int *p) ;

3. func()
:

13.

411

/ / !
void funcO
{

asm ("mov bp, sp"};

asm {"push ax");


asm ("mov cl, 4 " ) ;


. , .

{
,
.

13.7.
/
/ , C++
,
. / (array-based I/O)
C++ / (
sscanfQ sprintf() ), /
C++ ,
.
/ , .
, / . , / C++ 8
9 / . ,
/, .

412

C++

. , /
, .
/, , <strstream>. istrstream,
ostrstream strstream. , ,
, /.
ios,
istream, ostream iostream istrstream,
ostrstream strstream.

ostrstream:
ostrstream _ (char *, streamsize ,
opemnode = ios: :out) ;

_ , , . .
, , ios,
. ( 9.)
, . .
/.

- pcount():
int pcountO ;


, , .
,
istrstream:
istrstream _

(const char

*);

, .
_. , eof()
.
/,
strstream:
strstream __* (char *, streamsize ,
openmode = ios : : in | ios: : out) ;

13.

413

___ /,
/
.
, /
, /
.
.


Standard C++. ,
,
C++ . ,
, Standard C+ +
-, 14.

- -

1. , :
//
tinclude <iostream>
^include <strstreara>
using namespace std;
int

main()
char buf[255]; //
ostrstrearn ostr(buf, sizeof buf}; //
ostr "/ \";
ostr " , /\ " 100;
ostr ' ' 123.23 '\';
//
ostr hex 100 ' ';
//
ostr.setf(ios::scientific};
ostr 123.23 '\n';
ostr ends;
//
cout buf;
return 0;

414

C++
:
/
, /
100 123.23
64 01.2323+02

, /,
/, -
/ . ( /,
.)
ends
. , . ,
, .
2. :
//
#include <iostream>
#include <strstream>
using namespace std;
int main ( )
char buf[] = " 100 123.125 a";
istrstream istr(buf); //
int i ;

char str[80];
float f;
char c;
istr str i f c;
cout str ' ' i ' ' f;
cout ' ' '\n';
return. 0;
, , buf.
3. , , , . ,
buf eof() get():

13.

415

/* , eof() get()
/,
*/
'
tinclude <iostream>
#include <strstream>
using namespace std;
int main {}
{
char b u f [ ] = " 100 123.125 a";
istrstream istr(buf);
char c;
while(listr.eof( t
istr.get(c);
if (!istr.eof()}cout c;
return 0;

4. :
// /
^include <iostream>
finclude <strstrearn>
using namespace std;
int mainO
{

char iobuf[255];
strstream iostr (iobuf, sizeof iobuf);
iostr " \n";
iostr 100 hex ' ' 100 ends;
char str[80];
int i;
iostr.getline(str, 79); // \
iostr dec i; // 100
cout str ' ' i ' ';
iostr hex i;
cout hex i;
return 0;

416

iobuf, a
. getline()
" " ,
100, 0x64.

__1_^
1. 1 , , buf.
2. /,
. ( .)
3. /,
, ,
.




.
1. - ?
2. , / ?
3. , /
/ ,
"" /?
4. counterQ ,
.
5. ?
6. explicit.
7. -?
8. .
9. mutable?

13.

417



, .
1.
, , , ?
2. - const_cast,
-
?
3. : C++
C++
,
std " "?
4. . ,
- . ,
?

14

! , C++.
C++ (Standard Template
Library, STL).
C++, , ,
. , , . , (vectors), (lists),
(queues) (stacks). .
-,
.
, , C++.
,

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

420

C++

, ,
. , , , . ,
, .

C++ (string class). ,
, .

,
.
1. , C++ .
2. -?
3. mutable ()
. ?
4. :
class X {
int a, b;
public:
X(int i, int j)

{ a = i, b = j;

//

};
,
.
5.
. ?
6. :
class Demo {
int ;
public:
explicit Demo (int i) { a = i; }
int geta() { return a; }

:
Demo = 10;

14.

42?

14.1.

,
, , ,
.
.

: , . ,
.
(containers) , . . ,
vector () , queue
() , list () .
, (associative containers), (keys) . ,
( ) ,
. ,
/, .
-
. , , (merge) . .
(algorithms) .
, ,
.
(sequence), .
(iterators) ,
.
,
. , :


(random access)

(bidirectional)

422

C++
()

(forward)

(input)

{output)

( . / , . . ,
, . . , . .)
,
. ,
.
, .
. *. iterator, .
(reverse iterators). , , . ,
, ,
.
,
:

Randlter
Btlter

(random access)
(bidirectional)

Forlter
Inlter
Outlter

(forward)
(input)
(output)

, , .
, .

14.

423


(allocator),
.
allocator, ,
- . , .
,
(predicate).
. , . .
. , , UnPred, BinPrcd.
: , .
,
.
, .
(comparison function). , .
.
-,
, C++
<utility> <functional>,
-. , <utility> - pair (), . pair.
<functional> ,
- operatorQ. - (function objects) . <functional> -,
:
plus

minus

multiplies

divides

modulus

negate

equal_to

not_equal_to

greater

greater_equal

less

less_equal

iogical_and

logical_or

logical_not

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

C++

424

. ( ) - . - ,
. , .

1. , ,
?
2. ?
3. ?

14.2. -
,
,
. . 14.1 ,
, ,
, .
, , , .
14.1. ,

bitset

<bitset>

deque

<deque>

<list>

list
map


/,

<>

multimap


/,

<>

multiset

<set>

pnonty_queue

<queue>

queue

<queue>

14.

425
14.1 ()

set

<set>

stack

<stack>

vector

<vector>

, -,
, -
typedef .
.
, typedef, :

size_type

, size_t

reference

const_reference

iterator

constjterator

reversejterator

const_reverse_iterator

value_type

allocator_type

key_type

key_compare

value_compare

, : , . , , .

14.3.
, . vector
. , .
, C++ -

426

C++

. , ,
. ,
. ,
, , ,
,
.
vector:
template<class , class Allocator = allocator<Tclass vector

,
Allocator , . vector :
explicit vector(const Allocator a = Allocator{));
explicit vector (size_type , const ^ = () ,
const Allocator &a = Allocator());
vector(const vector<T, Allocator>);
template<class InlterXvector(Inlter , Inlter ,
const Allocator &a = Allocator {)>;

.
, .
. , .
, , .
, , . ,
< =. . (
.)
.
,
. :
vector<int> iv;

//

vector<char> cv(5); //

14.
vector<char> cv(5,

427

'x'); //
//

vector<int> iv2(iv);

//
//

vector :

=, <, <=, !=, >, >=


vector [], , .
. 14.2 vector. (,
.) sizeQ, begin(), end(), pushJbackQ, inscrt()
erase(). sizeQ .
, . , , , .
beginQ . end() . , beginQ end()
(: ) .
pushJbackQ . , . insertQ.
. , ,

.
erase().
14.2. vector
-

template<class lnlter>
void assign(lnlter ,
inlter );

template<class Size, class T>


void assign(Size ,
const & - (;

reference at(slze_type /");


const_reference
at(size_type i) const;

,
I

+-

428

14.2 ()

reference backf);
const_reference back() const;

iterator beginO;
const_iterator beginf) const;

size_type capacltyO const;

, . .
,

void clearf);

bool empty() const;

,
,

iterator end();
const_iterator end() const;

iterator erase(lterator i);

, i. ,

iterator eraseflterator ,
iterator };

, .
,

reference front();
const_reference front() const;

allocator_type
get_allocator() const;

iterator insertflterator /,
const & = T(;

, i.

void insert(iterator /,
size_typc ,
const );


, /

template<class lnlter>
void insert(iterator /,

,
,
, i

slze_type max_slze() const;

reference operatorl]
(size_type /) const;
const_reference operator!]
(slze_type /) const;

,
i

void pop_back();

void push_back(const

Inlter ,
Inlter );

&);

14.

429

14.2 ()
-

reversejterator rbegin();
const_reverse_lterator
rbeginf) const;

reverse_iterator rend();
const_reversejterator
rend() const;

void reserve(size_type );

,
,

void resize(size_type ,


.
,
,

size_type sized const;

void swap(vector<T,
Allocator> &);

, ,

= T());

1. ,
.
//
tfiriclu.de <iostream>
# include <vector>
using namespace std;
int main ( )
vector<int> v; //
int i;
// v
cout " = " v.size(} endl;
// ,
//
for(i=0; i<10; i++) v.push back(i);
// v
cout " = " v . s i z e O endl;

430

C++

/I v
cout " : \";
for(i=0; i<v.size{); i++) cout v[i] " ";
cout endl;
// ,
/ /
for(i=0; i<10; i++) v.push_back (i+10) ;
//
cout " = " v. size endl;
//
cout " : \";
for(i=0; i<v.size(); i4+) cout v[i] " ";
cout endl;
//
for(i=0; i<v. sized; i++) v[i] = v[i] + v[i];
//
cout " : \" ;
for(i=0; i<v.size(); i++) cout v[i] " ";
cout endl;
return 0 ;

:
=
= 10
:
0 1 2 3 4 5 6 7 8 9
= 20
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
:
2 4 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38

. main() v
. ,
,
. - size(). - push_back() v . , v . ,
10. v. ,
. -

14.

43?

, , . , .
- . , v.sizeQ
v.
,
. , ,
2. , C++ .
, .

. , . .
//
^include <iostream>
^include <vector>
using namespace std;
int main { }
{

vector<int> v; //
int i;

//
for (1=0; 10; 1+- v,push_back (i) ;
//
//
for{i=0; i<10; i++) cout v[i] " ";
cout endl;
//
vector<int>: : iterator p = v.beginO;
while{p != v.end)} {
cout *p " ";
P++;
return 0;

:
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9

432

C++

v .
- push_back() v v .
. iterator
-. , , , :
iterator . beginQ , . . , ,
.
.
- end() . ,
, ,
v.end(), , .
3. ,
- insert() .
- erase().
// insert() erase ()
tinclude <iostream>
^include <vector>
using namespace std;
int
(

main()
vector<int> v(5, 1); //
//
int i;
//
cout " = " v.sizef) endl;
cout " :\";
for(i=0; i<v.size(}; !+<-) cout v[i] " ";

cout endl;
vector<int>::iterator p = v.begin{);
p += 2; //
// ,
// ,
// 9
v.insert(p, 10, 9) ;
//
//
cout " = " v.sizeO endl;

14.

433

cout " :\";


for(i=0; i < v . s i z e ( ) ; i++) cout v[i] " ";
cout endl;
//
p = v.begin () ;
p += 2; //
v.erase{p, -); //
// ,
//
//
,,
//
cout " " v.sizeO endl;
cout " :\";
for{i=0; i<v.size(); i++) cout v[i] " ";
cout endl;
return 0;

:
= 5
:
11111
= 15
:
1 1 9 9 9 9 9 9 9 9 9 9 1 1 1
= 5
:
11111
4. ,
. , <
==. , , ,
.
//
#include <iostream>
#include <vector>
using namespace std;
class Demo {
double d;

C++

434

public:
Demo () { d = 0.0; }
Demo (double x) { d = x; }
Demo ^operator- (double x) (
d = x; return ''this;

}
double getd() (return d; }
boll operator< (Demo a, Demo b)
{
return a.getdf) < b.getdf);
1
boll operator (Demo a, Demo b}
{
return a.getd() == b.getdO;
}
int mainO

{
vector<Demo> v;
int i;
for{i=0; i
v.push_back(Demo (i/3. 0) ) ;
for (i=0; Kv.size () ; i
cout v [ i ] . g e t d ( ) " ";
cout endl;
for(i=0; i < v . s i z e ( } ; i++)
v[i] = v[i] .getdO * 2.1;
for (i=0; Kv.size () ; i
cout v [ i ] . g e t d ( ) " ";
return 0;

:
0.333333 0 . 6 6 6 6 6 7 1 1.33333 1.66667 2 2.33333 2 . 6 6 6 6 7 3
0.7 1.4 2.1 2.8 3.5 4.2 4.9 5.6 6.3

]
1. .
.

14.

435

2. 4 Demo ( ) . , ?
3. Coord.
Coord . (: Coord < ==.)
class Coord (
public:
int x, ;
Coord(} { x = = 0; }
Coord(int a, int b) { x = ; = b;

14.4.
list .
, ,
.
, .
list:
template<class T r class Allocator = allocator<Tclass list

, , Allocator ,
. list
:
explicit list(const Allocator Sa Allocator());
explicit list (size_type , const & = TO f
const Allocator &a = Allocator{));
list(const list<T, Allocator>);
template<class Inlter>list{Inlter , Inlter ,
const Allocator fia = Allocator<));

. , ,
, . , .
, , .

C++

436

list :

==, <, <=, =, >, >=


. 14.3 list. pushJbackQ (
), push_front(),
insert(). (Join) splice(), (merge) merge().
, ,
. , .
, ,
,
.
14.3. list

template<class lnlter>
void assignflnlter ,
Inlter );

template<class Size, class T>


void assign (Size ,
const & - T());

reference b a c k ( ) ;
const__reference backf) const;

iterator beginf);
constjterator begin() const;

void clear();

bool emptyO const;

,
,

iterator cnd();
const_iterator end() const;

Iterator erasefiterator /);

, /. ,

iterator erasefiterator ^
iterator );

, .
,

reference frontf);
const_reference front() const;

allocator_type
get_allocator() const;

14.

437

14.3 ()

iterator insertflterator i,
const & = ());

, /.

void insert(iterator j,
size_type ,
const &);


, i

template<class lnlter>
void insert(iterator /,
Inlter ,
Inlter );

,
,
, i

size_type max_size() const;

void merge(list<T,
Allocator> &);
template<class Comp>
void merge(llst<T,
Allocator> &,
Comp ^);

,
, . . , .
, ,
,
_

void pop_back();

void pop_front();

void push_back(const

^);

void p u sh__f nt( const


& );

reversejterator rbeginf);
const.reversejterator
rbeglnO const;

void remove(const

template<class UnPred>
void remove_lf(UnPred );

reversejterator rend();
const_reverse_iterator
rendO const;

void resize(size_type ,
= T());


.
,
,

void reverse!);

(. .
)

&);

C++

438

14.3 ()

sizejtype size() const;

void sort();

. ,
, ,

template<class Comp>
void sort Comp _);

void splicefiterator /,
list<T, AHocator> &);

. /.

void spllcefiterator i,
list<T, Allocator> &,
iterator );

, , ,
, .
/

void splicefiterator /,
list<T, Allocator> ,
iterator ,
iterator );

,
, ,
,
.
/

void swap(list<T,
Allocator> & );

void unlque();
template<class BinPred>
void unique(BinPred );

1. .
//
^include <iostream>
^include <list>
using namespace std;
int main i)
list*^char> 1st; //

int i;
for{i=0; i<!0; i++) 1st .push_back ( 'A' + i)
cout " = " 1st. size () endl;

14.

439

list<char>::iterator p;
cout ": ";
while(!1st.empty(}) {
p = lst.begin();
cout *p;
1st.pop f r o n t ( ) ;
return 0;

:
= 10
: ABCDEFGHIJ
. . ( J ).
push_back(), . .
, , .
, .
2. , , . , , .
.
#include <iostream>
^include <list>
using namespace std;
int main{)
list<char> 1st;
int i;
for{i=0; i<10; i++) 1st-push_back('A1 + i};
cout " = " 1st.size () endl;
list<char>::iterator p = lst.begin{);
cout ": ";
while(p != 1st.end(}) {
cout *p;

440

C++
return 0;

J.
,
, , .
, .
3. ,
, . ,
.
// ,
//
^include <iostream>
^include <list>
using namespace std;
int main()
(
list<char> 1st;
list<char> revlst;
int i;

for(i=0; i<10; i-H-) 1st .push_back ('A' + i) ;


cout " = " 1st.size () endl;
cout " : ";
list<char>;:iterator p;
//
//
while(!1st.empty{)) {
= 1st.begin();
cout *;
1st.pop_front!);
revlst.push_front(*p);
}

cout endl;
cout " = ";
cout revlst.size() endl;
cout " : ";
= revlst.begin();
while( != revlst.end{)) {
cout *p;
P+-H;

14.

_ 447

return 0;
1

:
= 10
: ABCDEFGHIJ
= 10
: JIHGFEDCBA
1st : 1st
revlst. revlst
.
4. - sortQ, .
, .
//
^include <iostream>
^include <list>
tinclude <cstdlib>
using namespace std;
int main()
{

list<char> 1st;
int i ;
//
for(i=0; i<10; i++) 1st .push_back ( 'A' + (rand { ) %26) } ;
cout " : " ;
list<char>: : iterator p = Ist.beginf);
while (p != 1st. end!) ) {
cout *p;
cout endl;
//
1st . sort ( } ;
cout "
p = lst.begin() ;
while (p != 1st. end () ) {
cout *p;

442

C++

return 0;

:
: PHQGHUMEAY
: AEGHHMPQQY

5. .
,
. ,
.
. ACEGI, BDFHJ.
ABCDEFGHIJ.
//
^include <io5tream>
#include <list>
using namespace std;
int main ( )
{
list<char> Istl, Ist2;
int i;
for (1=0; i<10; i+=2) Istl .push_back ( 'A1 + i) ;
for (1=1; i<ll; i+=2) Ist2 .push_back ( 'A' + i) ;
cout " :
list<char>; : iterator p = Istl. begin (
while(p != Istl. end () ) (
cout *p;

P++;
}
cout endl;
cout " :
p - Ist2.begin() ;
whileip != Ist2.end()) {
cout *p;

cout endl;
//
Istl.merge(Ist2);
if {Ist2.empty() )
cout " \";

14.

443_

cout " :\";


= Istl. begin ( ) ;
while (p 1= I s t l . e n d O ) {
cout *p;

return 0;

:
: ACEGI
: BDFHJ

:
ABCDEFGHIJ

6.
Project. Project ,
. , Project
<, >, != ==.
Microsoft Visual C+4- 5. (
.) - . - , . ,
, .
^include <iostream>
^include <list>
#include <cstring>
using namespace std;
class Project {
public:
char name [40] ;
int days_to_completion;
ProjectO {
strcpy (name, " ") ;
days__to_completion = 0;
}
Project (char *n, int d) {
strcpy {name, n) ;
days_to_completion = d;
\

444

C++

void add_days(int i) (
days_tcj_completion += i;
void sub_days(int i) {
days_to_completion -= i;

}
bool completed() { return !days_to_completion; }

void report() {
cout name ": ";
cout days__to_completion;
cout " \";

bool operator<(const Project &a, const Project sb)


return a,days_to_completion < b.days_to_completion;
bool operator>(const Project &a, const Project &b)

return a.days_to_completion > b.days_to_completion;

bool operator==(const Project &a, const Project &b)


return a.days_to_completion == b.days_to_completion;

}
bool operator!=(const Project &a, const Project &b)
return a.days_to_completion != b.days_to_completion;
int main()
list<Project> proj;
proj.push_back(Project(" ", 35});
proj.push_back(Project(" ", 190))
proj.push_back(Project{" STL", 1000});
list<Project>::iterator p = proj.begin(};
//
while (p != proj.endO) {
p->report(};
P++;

14.

445

// 10
= proj.begin();
p~>add_days{10);
//
do {

p->sub_days(5);
p->report () ;
} while (!p->completeci{) ) ;
return 0;

:
: 35
: 190
STL: 1000
: 40
: 35
: 30
: 25
: 20
: 15
: 10
: 5
: 0

1. .
.
2. 1 .
2 ,
. , ?
, 1.
3. 6, , :

780
50
300

446

C++

. .

14.5.
, . , ,
.
, . ,
,
/. . , ,
, .
.
, . . -
multimap.
:
template<class Key, class , class Comp = less<Key>,
class Allocator = allocator<Tclass map

Key , ,
( ), a Comp - ,
- lessQ,
Allocator (
allocator).
:
explicit map (const Comp &_ = ,
const Allocator Sa = Allocator());
map (const map<Key, T, Comp, Allocator>fiooieJC!r) ;
teroplate<class Inlter>map(Inlter , Inlter ,
const Comp &_ = CompO , const Allocator &a = Allocator ()) ;

.
, . , , . _,

14.

447

, .
, , ,
.
:
= = , <, <=, !=, >, >=

. 14.4 .
key_type , a key_value / (
pair < Key, T>).
14.4.

iterator beginf);

constjterator begin() const;


void clear();

size_type count
(const key_type &k) const;

1 0, ,

k

bool emptyO const;

, ,

iterator end();
const_iterator end() const;

pair<iterator, lterator>
equal_range (const
key_type &k);
pair<const_iterator,
const_Iterator>
equal_range(const
key^type &k) const;

, ,
k

void erase(iterator /);

, i

void eraseflterator ,
iterator );

size_type erase
(const key_type &k);

,
k

iterator find
(const key_type &k);
constjterator find
(const key_type &k) const;

.
,

allocator_type
get_allocator() const;

C++

448

14.4 ()

iterator insertffterator /,
const value_type ^);

, i".

template<class lnlter> void


Ensert(lnlter ,
Inlter );

paiKiterator, bool>insert
(const value_type &);

. . , .
pair<iterator,
true>, paiKiterator,
false>

key_compare key_comp() const;

iterator lower_bound

,
k

size_type max_size() const;

reference operator[]
(const key_type &i);

, I. ,

reverse_iterator rbegin();
const_reverse_iterator

reversejterator rendf);
const_reverse_lterator

size_type size() const;

void swap(map<Key, T, Comp,


Allocator> & );

iterator upper_bound

(const key_type &.k);


constjterator upper_bound

,
k

value_compare
value_comp() const;

(const key_type &fc);


constjterator lower_bound
(const key_type &k) const;

rbegin() const;

rend() const;

(const key_type &k) const;

14.

449

/
pair. pair :
template<class Ktype, class Vtype> struct pair {
typedef Ktype _; //
typedef Vtype ; //
Ktype ; //
; //
/ /
pair () ;
pair (const Ktype &k, const Vtype fiv) ;
template< class A, class B> pair (const<A, B> &)

,
, , .
/
pair,
pair,
make_pair()


make_pair(),
.
:

template<class Ktype, class Vtype>


pair<Ktype, Vtype>make_pair (const Ktype fit, const Vtype fiv) ;

, pair,
Ktype Vtype.
make_pair() ,
, .

, /, . , . / :

2
. . .

, , (. . J),
.

450

++

II
^include <iostream>
^include <map>
using namespace std;
int main{}
{
map<char, int> m;
int i ;
//
for(i=0; i<10; i++) {
m. insert !pair<char, int>('A' + i, i) ) ;
1
char ch;
cout " : ";
cin ch;
map<char, int>: : iterator p;
//
= m. find(ch) ;
if (p != m.endO }
cout p->second;
else
cout " \";
return 0;

- pair
/. , - pair,
, .
/, findQ. find() ,
. ,
- pair.
2. / pair<char, int>. ,
make_pair(),
.
^include <iostream>
^include <map>
using namespace std;

14.

451

int main { )
{

map<char, int> m;
int i;

//
for(i=0; i<10; i++) {
m. insert {make__pair (char) ( ' A ' H- i, i) ) ;
char ch;
cout " : ";
in ch;
map<char, int>: : iterator p;
//
= m. find(ch) ;
if ( !- . end () )
cout p->second;
else
cout " \";
return 0;


m. insert (make_pair (char) ( ' A ' + i, i) ) ;
, '* + i int, char.
.
,
. ,
. : word ()
opposite ().
, word <. , <
, . ( <
.)
//
tinclude <iostream>
# include <map>
#include <cstring>
using namespace std;

452

___________

class word {
char str [20];
public:
wordO { strcpy(str, ""); }
word(char *s) { strcpyfstr, s); }
char *get() { return str; }
// word < ()
bool operator< (word a, word b)
{
return strcmp(a.get {) , b.getO) < 0;
}
class opposite {
char str [20] ;
public:
opposite!) { strcmp(str, ""); }

opposite (char *s) ( strcpyfstr, s) ; }


char *get() { return str; }
)!

int main()
{
map<word, opposite> m;
//
m. insert (pair<word, opposite>
(word ("") , opposite ("") } ) ;
m. insert (pair<word, opposite>
(word ("") , opposite ("") } ) ;
m. insert {pair<word, opposite>
(word ("") , opposite ("") ) ) ;
m. insert (pair<word, opposite>
(word ("") , opposite ("") } ) ;
//
char str [80] ;
cout " : ";

cin str;

map<word, opposite>: : iterator p;


p = m. find{word(str) ) ;
if (p != m.endO )
cout ": " p->second.get () ;
else
cout " \";

C++

14.

453

return 0;
i

, ,
. , , string.

1. .
.
2. . ,
. (: 3.)
3. <, ?

14.6.
, .
, . ,
.
<algorithm>.
, . 14.5.
-. , . .
14.5.

adjacentjflnd

bfnary_search

C++

454

14.5 ()

copy

copy_backward

{), ,

count

count_If

equal
equal_range


,
,

fill

find

find_end

find_first_of

findjf

for_each

generate
generate.n

includes

inplace_merge

.

.

iter_swap

,
,

lexicographical_compare

lower_bound

make_heap

(, heap,
, ,
. . .)

14.

455

14.5 ()

max

max element

merge

mln

min_element

mismatch

next_per mutation

nth_element

,
,
, , , ,

parti assort

partial_sort_copy

, ,

partition

,
, , ,

pop_heap

prev_permutation

push_heap

random_shuffle

remove
remove_lf
remove_copy
re m ove_co py_if

replace
replacejf
replace_copy
replace_copy_if

reverse
reverse_copy

(permutation)

C++

456

14.5 ()

rotate
rotate_copy

search

search_n



,
,

,

,
(union)

set_difference
set_intersection
set_symmetric_dif fere nee
set_unlon
sort

sort_heap

stable^partition

,
, , ,
.
;

.

stable_sort
swap

swap_ranges

transform

unique
unique_copy

upper_bound

[
l

"""'''"^f

1. count()
coimt_if(). :
template<class Inlter, class T>
size_t count(Inlter ,
Inlter , const

14.

457

template<class Inlter, class T>


size_t count (Inlter ,
Inlter , UnFred &_) ;
count() ,
, , , , . countJfO ,
,
_ .
count() count_if().
// count count_if
^include <iostream>
ttinclude <vector>
^include <algoritm>
using namespace std;
/* , ,

*/

bool even(int x)
{
return ! (x%2) ;
int main { }
{
vector<int> v;
int i ;

for{i=0; i<20;
i f ( i % 2 ) v.push_back(l) ;
else v.push_back(2) ;
cout ": ";
for(i=0; i<v.size(}; i--) cout v[i]
cout endl;

int n;
n = count ( v. begin () , v.end(), 1);
cout n " 1\";
n = count_if (v. begin () , v.endO, even)
cout n " \";
return 0;

458

C++

:
:
10 1
10

2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1

20- , 1 2.
count (), count_if() ,
even(). , ,
, .

.
2. ,
. remove_copy(), :
template<class Inlter, class Outlter, class T>
Outlter remove copy (Inlter ,
Inlter , Outlter , const ) ;
remove_copy() , ,

, . . .
remove_copy().
1 2. .
// remove_copy
ttinclude <iostream>
tfinclude <vector>
^include <algorithm>
using namespace std;
int main( )
{

vector<int> v, v2(20);
int i;

for(i=0; i<20;
i f ( i % 2 ) v.push_back(l) ;
else v.push__back{2) ;

14.

459

cout ": ";


for(i=0; Kv.sizeO; i++) cout v[i] " ";
cout endl;
//
remove_copy ( v . begin () , v.end() , v2 .begin {) , 1) ;
cout ": ";
for(i=0; i<v2.size(); i++) cout v2[i] "
cout endl;

return 0;

:
:
2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1
: 2 2 2 2 2 2 2 2 2 2 0 0 0 0 0 0 0 0 0 0
3. reverse(), .
:
template<class Bilter>
void reverse (Bitter , Bilter ) ;
reverse()
, .
reverse().
// reverse
^include <iostream>
#include <vector>
^include <algorithrn>
using namespace std;
int main{)
{
vector<int> v;
int i;
for(i=0; i<10,- i++) v.push_back(i) ;
cout " : " ;
for(i=0; i<v. size(); i++) cout v[i] " ";
cout endl;
reverse (v. begin ( ) , v.end(} ) ;
cout " : ";
for(i=0; Kv.sizeO; i++) cout v[i] " ";
return 0;

460

C++

:
: 0 1 2 3 4 5 6 7 8 9
: 9 8 7 6 5 4 3 2 1 0

4. transform(),
. transform()
:
template<class Inlter, class Outlter, class FunO
Outlter transform (Inlter , Inlter ,
Outlter , Func _^) ;
template<class Inlterl, class Inlter2, class Outlter, class Func>
Outlter transform (Inlterl !, Inlterl !,
Inlter2 2, Outlter , Func _) ;

transform() , .
,
_. .
_,
, . .
xformQ,
. , , .
// transform
^include <iostream>
#include <list>
^include <algorithm>
using namespace std;
//
int x f o r m f i n t i) {
return i * i; //
int main ()
{
list<int> xl;
int i;

14.

461__

II
for (1=0; i<10; 1++) xl .push_back (i) ;

cout " xl: ";


list<int>: : iterator p = xl.beginO;
whiletp !=xl.end()) {
cout *p " ";
P++;
cout endl;
// xl
p = transform(xl. begin () , xl.endf), xl. begin (), xform) ;
cout " xl: ";
p = xl. begin () ;
while (p != xl.endO) {
cout *p " ";

return 0;

:
xl: 0 1 2 3 4 5 6 7 8 9
xl: 1 4 9 16 25 36 49 64 81

, xl.

sort() :
template<class Randlter>
void sort(Randlter , Randlter );
template<class Randlter, class Comp>
void sort(Randlter , Randlter ,
Comp _&);

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

462

C++

2. merge() , .
:
template<class Inlterl, class Inlter2, class Outlter>
Outlter merge(Inlterl !, Inlterl !,
Inlter2 2, Inlter2 oxonva*use2, Outlter ) ;

, , !, ! 2, 2.
.
.
.

14.7.
, C++
. . -, .
( string). ,
, string.
, string basic_string. basic_string : string, 8- , wstring, .
8- , string
basic_string.
string, ,
C++. C++
. ,
. C++
string ,
C++ . , :
C++ C++. , :
char si[80], s2[80], s3[80];
si = ""; //
s2 = ""; //
s3 = si + s2; // ,

14.

463

, C++ , ( ),
. :
strcpy(si,
Strcpy{s2,
strcpy{s3,
strcpy (s3,

"");
"");
si);
s2);

,
C++. ,
. C++
. , C++ ,
, C++. , . , C++ string,
, , .
, ,
string . ,
. , strcpy(). ,
.
, , (
) .
, string .
, C++ string :
( ), (
C++) ( ). , , . . ,
, string C++
.

464

++

, , C++ . , , ,
. ,
. string,
<string>.
string , -. - .
string. , .
string , .
string . , :
String () ;
string(const char *);
string(const string );

string. string , .
string. string string.
,
string:

+=

!=

<

<=

>

>=

[]

i_?4,

465

string ,
, strcpyQ strcatQ, , string
, . , string .
+ string
string string
. :
string + string
string + C-string
C-atring + string

, + .
string npos, -1.
.
, , string.
,
. assign (). :
string Sassign(const string &_,
size_type , siza__type ) ;
string Sassign(const char *, size_type );

,
_, ,
. ,
. . ,
=. assign .
append(). :
string fiappend (const string _!,
size_type , size_type ) ;
string Sappend(const char *, size__type ) ;

,
_,
. -

466

C++

,
, .
. , +.
appendQ
.
insert() replaceQ
.
:
string &insert(size_type , const string _!) ;
string fiinsert(size_type , const string &_,
size_type _, size_typa );
string fireplace (size_type , size_type ,
const string ) ;
string fireplace (size_type , size_type _,
const string &_,
size type , size type ) ;

insertQ _ . insert()
__, _,
.
replace() , , ^.
replaceQ _ , , _ _ , _. .
eraseQ. :
string fierase(size_type = 0, size_type = npos);

,
. .
string -, . find() rfindQ.
:
size_type find (const string __,
size_type = 0) const;
size_type rfind (const string &<_,
size_type = npos) const;

14.

467^

find() , _.
, find()
, .
, fmd() npos.
find(), rfindQ, ,
, ,
_. ( , _.)
, rfindQ ,
. , iTind() npos.
. ,
, - (). :
int compare(size_type ,

size_type ,
const string 6!_)

const;

_, . ,
_, compareQ .
, ^, ()
. _, () .
string ,
,
. , string
.
, . string - c_str(),
:
const char *c_str() const;

,
string.
. , string - ,
c_str() .
string , beginQ end(),
. sizeQ, .

468

C++

1.^
, C++
string . ,
string
, +, . .
//
^include <iostream>
ttinclude <string>
using namespace std;
int
(

main()
string strl(" "};
string str2(" ");
string str3;
//
str3 = strl;

cout strl "\n" str3 "\n";


//
str3 = strl + Str2;
cout str3 "\n";
//
if(str3 > strl) cout "str3 > strl\n";
if(str3 == strl+str2) cout "str3 strl+str2\n";
//
strl = " \";
cout strl;
//
//
string str4(strl);
cout str4;
//
cout " : ";

cin str4;
cout str4;
return 0;

14.

469


str3 > strl
str3 == strl+str2


:

, string ,
C++. , , .
: +, >.
,
strcat() strcmp(), , , . string
,
, , , .
, : . string . , ,
,
. string
. ( ,

).
2. insert(), erase()
replace ().
// insert , erase () replace ()
^include <iostream>
^include <string>
using namespace std;
int main()
{
string strl(" ");
string 5^2("") ;

cout " :\"


cout "strl: " strl endl;
cout "str2: " str2 "\n\n";
// insert(}
cout " str2 strl:\n"

470

C++

strl, insert (4, str2) ;


cout strl "\n\n";
// erase ()
cout " strl:\n"
strl. erase (4, 1} ;
cout strl "\n\n";
// replace ()
cout " strl str2:\n"
strl.replace(4, 8, str2) ;
cout strl "\n\n";
return 0;

:
:
strl:
str2:
str2 strl:

strl:

strl str2 :

3. string , string. ,
, 3
14.5.
/* string
*/
^include <iostream>
#include <map>
^include <string>
using namespace std;
int main ( )
{
map<string, string> m;
int i;
m, insert (pair<string, string> ("", "") ) ;
m. insert (pair<string, string> ("", "",) ) ;
m. insert (pair<string, string>( "") , "") ) ;
m. insert (pair<string, string> ("") , "") ) ;

14.

4_71_

string s;

cout " : ";


cin s;
map<string, string>: : iterator p;
p = m. find(s) ;
if (p != m.endO )

cout ": " p->second;

else
cout " \";
return 0;

string :

.
string ,
. ,
. count()
"" .
2 , . (: count_if().)
string -. ?

j
I

~^


.
1.
?
2. , .

472

__

C++

3. 10- ,
1 10.
.
4. string? ?
5. ?
6. 2 14.5 ,
string.
7. - .
unary_function nary_fiinction, -.
8. , . .



, .
1. 1, .
. , ( ) C++.
2. .
C++.
, .
3. .
, , , , .
4. . : C++
.
C++ . , ,
.
C++ , ,
, ,
.

C++
C++
( ANSI ),
C++.
, 1. , :
, C++ ,
, C++ .
Q , ,
, .
C++ .
Q 31 . C++ .

- .
main() ,
- .
C++ main() .
(
register), C++ .
Q wchar_t typedef. C++
wchar t .



( ) .
. , , .

1.3
1. ttinclude <iostream>
using namespace;
int main()
I

double hours, wage;


cout " : ";
cin hours ;
cout " : ";
cin wage;
cout " : $" wage * hours;
return 0;

2. #include <iostream>
using namespace std;

476

__

___

__

C++

int main ()
I

double feet;
do {
cout " (0 ) : ";
cin feet;
cout feet * 12 " \";
} while (feet != 0.0} ;
return 0;

3. I*
V
#include <iostream>
using namespace std;
int main ( )
{
j
int a, b, d, min;
cout " : ";
cin a b;
min = a > b ? b: a/-

for (d=2; d<min; d4-+)


if(a%d)==0) && ((bld)=0)) break;
if {d==rain) {
cout " \";
return 0;
}
cout " " d "\n";
return 0;

1.4
1. , , .

1.5
2. ^include <iostream>
^include <cstring>
using namespace std;

class card {
char title[80]; //
char author[40]; //
int number; //
public:
void store(char *t, char *name, int num);
void show();
void card::store(char *t, char *name, int num)
i
strcpy(title, t);
strcpy(author, name);
number = num;
void card: :show().

cout ": " title "\n";


cout ": " author "\n";
cout " : " number "\n";
int main()
card bookl, book2, bookS;
bookl.store("Dune", "Frank Herbert", 2);
book2.store("The Foundation Trilogy", "Isaac Asimov", 2);
books.store("The Rainbow", "D. H. Lawrence", 1);
bookl. show{) ;
book2. show() ;
bookS. show{) ;
return 0;

3. ^include <iostream>
using namespace std;
#define SIZE 100
class q_type (
int queue[SIZE]; //
int head, tail; //
public:
void i n i t ( ) ; //
void q(int num); //

477

478

int deq(); //

};
//
void q_type: :init ()
{
head = tail = 0;
//
void q_type: :q{int num)
{
if (tail + l-=head I I (tail + 1==SIZE && Ihead) ) (
cout " ";
return;

if (tail==SIZE) tail = 0; //
queue[tail] = num;

)
//
int q_type: :deq()
{
if (head==tail) (
cout " ";
return 0;

if (head==SIZE) head = 0; //
return queue [head];
int main ()
q_type ql, q2;
int i ;
q2.init() ;
for{i-l; i<=10; i
ql.q(i);
q2.q(i * i);
for(i=l; i<=10; i
cout " 1: " ql.deqO "\n
cout " 2: " q2 . deq ( ) "\n

C++

. it

return 0;

1.6
1. f() .

1.7
1. ^include <iostream>
^include <cmath>
using namespace std;
// sroot() integers, longs doubles
int sroot(int i);
long sroot(long i) ;
double sroot (double i);
int main(}
{
cout
cout
cout
cout
cout

" 90.34 : " sroot (90.34);


"\n";
" 90L : " sroot(90L);
"\n";
" 90 : " sroot(90);

return 0;
//
int sroot(int i)
{
cout " ";
return (int) sqrt((double)i);
//
long sroot(long i)
{
cout " \";
return (long) sqrt((double)i);
}
//
double sroot(double i)
{
cout " \";
return sqrt(i);
i

[79

480

__

__

__

C++

2. atof(), atoi() atol() , . , , .


3. // min()
^include <iostream>
#include <cctype>
using namespace std;
char min{char a, char b) ;
int minfint a, int b} ;
double min (double a, double b) ;
int main()
{
cout " : " min ( ' x ' , 'a') "\n";
cout " : " rninflO, 20) "\n";
cout " : " min{0.2234, 99.2} "\n";
return 0;

}
// chars
char min (char a, char b)
{
return tolower(a) < tolower(b) ? a: b;

}
// ints
int min (int a, int b)
{
return a < b ? a: b;
}
\
// doubles
double min (double a, double b)
{
return a < b ? a: b;

4. ^include <iostream>
using namespace std;
// sleep ( )
void s l e e p f i n t n) ;
void sleepfchar *n) ;
//
//
^define DELAY 100000

481

int main {)

coot
sleep (3) ;
cout ' . ' ;
sleep("2") ;
cout ' . ' ;
return 0;
// sleep ()
void sleep (int n)
{
long i;

for!; n; n )
for (1=0; i<DELAY;
// sleep () char *
void sleep (char *n)
{
long i;
int j;
j = atoi (n) ;

for(; j; j )
for(i-0; i<DELAY;

1
1. ,
. ,
.
. , .
.
2. C++ , ,

++.

3. #include <iostream>
using namespace std;

482

int main ( }
{
int b, e, r;
cout " : ";
cin b;
cout " : " ;

cin e;
r = 1;
for(; e; e } r = r * b;
cout ": " r;
return 0;

4. ^include <iostream>
#include <cstring>
using namespace std;
//
void rev_str(char *s); // s
void rev_str(char *in, char *out) ; //
// out
int main ()
{
char sl[80], s 2 [ 8 0 J ;
strcpy(sl, " ");

rev_str (si, s2) ;


cout s2 "\n";
rev_str{Sl);
cout si "\n";
return 0;
// s
void rev strfchar *s)
char temp [80] ;
int i , j ;
for(i=strlen(s)-l, j=0; i>=0; i~, j++)
temp [ j ] = s [ i ] ;
teinp[ j ] = '\0'; //
strcpy(s, temp);

C++

. ^
// out
void rev_str(char *in, char *out)
int i, j;

for(i=strlen(in}-l/ j=0; i>=0; i, j++)


out[ j ] = in[ i ];
out[ j ] = r\0'; //

5. ^include <iostream.h>
int f(int a);
int main(}
{
cout f(10);
return 0;
int f(int a)

return a * 3.1416;

6. bool .
true false.

2

1. ^include <iostreara>
#include <cstring>
using namespace std;
int min{>
i
char s[80];
cout " : ";
cin s;
cout " : " strlen(s) "\n";
return 0;

483

C++

484

2. #include <iostream>
#include <cstring>
using namespace std;
class addr {
char name[40J ;
char street [40] ;
char city[30] ;
char state [3] ;
char zip[10] ;
publ i :
void store(char *n, char *s, char *c, char *t, char *z);
void display () ;
);
void addr: : store (char *n, char *s, char *c, char *t, char *z)
\
strcpy(name, n) ;
strcpy ( street , s ) ;
strcpy {city, c) ;
strcpy(state, t) ;
strcpy (zip, z) ;

void addr: : display ()


{
cout name "\n";
cout street "\n";
cout city "\n";
cout state "\n";
cout zip "\n\n";
int main ( )
f
addr a;
a.store("J1. . ", " ", ".-",
"", "46576"};

a. display {) ;
return 0;

3. ^include <iostream>
using namespace std;
int rotate (int i);
long rotate (long i) ;


int

455

main(}

int a;
long b;

a = 0x8000;
b = 8;

cout rotate ( a ) ;
cout " \ n " ;
cout rotate ( b ) ;
return 0;
}

int rotate (int i)

{
int x;

if (i & 0x8000} x = 1;
else x = 0;

i = i 1;
i
_L

1 = v

return i;

>
long rotateflong i)

int x;
if (i S 0x80000000) x = 1;
else x = 0;

i = i 1;
i += x;
return i;

4. i myclass,
main()

2.1
1. ^include <iostream>
using namespace std;

486 _

ttdefine SIZE

100

class q_type {
int queue[SIZE]; //
int head, tail; //
public :
q_type ( ) ; //
void q{int num) ; //
int deq(); //
};
//
q_type: :q_type()
(
head = tail = 0;
//
void q_type: :q{int num)
i
if {tail + l==head I I (tail + 1==SIZE && Ihead}
cout " ";
return;

if (tail==SIZE) tail = 0; //
queue [tail] = num;
\

II
int q_type : : deq ( )
i
if (head==tail) {
cout " ";
return 0;
}
head++;
if (head==SIZE) head = 0; //
return queue [head] ;
int main ( )
{
q_type ql, q2;
int i;
for{i=l; i<=10;
ql.q(i) ;
q2.q(i * i) ;

C++

.
for (i=l; i<=10; H-+) {
cout " 1: " ql.deq() "\n";
cout " 2: " q2.deq() "\n";
}
return 0;
\

2. II
^include <iostream>
^include <ctime>
using namespace std;
class stopwatch {
double begin, end;
public:
stopwatch();
-stopwatch();
void start (};
void stop () ;
void show{) ;
stopwatch::stopwatch()
{.
begin = end = 0.0;
stopwatch::~stopwatch()
{
cout " stopwatch .,.";
show();
}
void stopwatch::start()
{
begin = (double) clock () / CLOCKS_PER_SEC;
I
void stopwatch::stop()
{
end = (double) clock(} / CLOCKS_PER_SEC;
}
void stopwatch::show()
{
cout " : " end begin;
cout "\n";
I

487

488

C++

int main (}
stopwatch watch;
long i;
watch.start() ;
for(i=0; K320000; i++) ; //
watch.stop();
watch.show();
return 0;
}

3. .

2.2
\. (I
^include <iostream>
^include <cstdlib>
using namespace std;
// stack
class stack {
char *stck; //
int tos; //
int size; //
public:
stack(int s); //
~stack(); //
void push{char ch); //
char pop(); //
//
stack::stack(int s)
t
cout " \";
tos - 0;
stck = (char *) malloc(s);
if (!stck) {
cout " \";
exit{l);
}
size = s;

.stack: :~stack (}
{

free (stck) ;

}
//
void stack: :push(char ch)
{
if (tos==size) {
cout " \";
return;
}
stck[tos] = ch;
tos++;

*
//
char stack:: pop ()
{
if (tos=0) {
cout " \";
return 0; //
)
tos ;
return stck [tos];
i
int main{)
{
// , ,
stack sl(10) , s2(10) ;
int i;

si. push { 'a' ) ;


s2.push('x');
si. push ( 'b' ) ;
s2.push('y');
si. push ( 'c' ) ;
s2.push('z');
for{i=0; i<3; i++) cout " si:" sl.popO
"\n";
for{i=0; i<3; i++) cout " s2:" s2.pop()
"\n";
return 0;

2. ttinclude <iostream>
^include <ctime>
using namespace std;

489

C++

490

class t_and_d (
time_t systime;
public:
t_and_d(time_t t) ; //
void show() ;
t_and_d : : t_and_d ( t ime_t t }
{
systime = t;
}
void t_and d::show()
{
cout ctime{fisystime)
}
int main()
'
time_t x;
x = time (NULL) ;
t_and_d ob{x) ;
ob . show { ) ;
return 0;

3. ^include <iostream>
using namespace std;
class box (
double 1, w, h;
double volume;
public:
box (double a, double b, double c)
void vol ( ) ;
box: :box (double a, double b, double c)
{
1 = a;
w = b;
h - c;
volume * 1 * w * h;

void box: :vol (}

cout " : " volume "\n";


}
int main()
{
box x(2.2, 3.97, 8.09), y(1.0, 2.0, 3.0);

x . vol { } ;
y.volf) ;
return 0;

2.3
1. #include <iostream>
using namespace std;
class area_cl {
public:
double height;
double width;
class rectangle: public area__cl (
public:
rectangle (double h, double w) ;
double area (} ;
class isosceles: public area_cl {
public :
isosceles (double h, double w) ;
double area () ;
rectangle:: rectangle (double h, double w)
{
height = h;
width = w;
}
isosceles :: isosceles (double h, double w)
{
height = h;
width = w;

491

492

double rectangle: : area ()


(
return width * height;
}
double isosceles : : area { }
{
return 0.5 * width * height;
}
int mainO
rectangle b(10.0, 5.0);
isosceles i(4.0, 6.0);
cout ": " b.areaO "\n"
cout ": " i.areaO "\n";
return 0;

2.5
1. // ,
#include <iostream>
using namespace std;
tdefine SIZE 10
// stack
struct stack {
stack(); //
void push(char ch); //
char pop ; //
private:
char stckfSIZE]; //
int tos; //
};
//
stack::stack()
(
cout " \";
tos=0;
1
//
void stack::push{char ch)

C++

493

'
if

(tos==SIZE) {
cout " \";
return;

stck[tos] = ch;
tos++;

//
char stack;:pop()
if (tos==0) {
cout " \";
return 0; //
tos;
return stck{tos];

int main()

i
// , ,
stack si, s2;
int i;
si.push('a');
s2.push('x');
sl.push('b1);
s2.push('y');
si.push('c1);
s2.push{'z'};
for(i=0; i<3; i++) cout " si:" sl.popO
"\n";
for(i=0; i<3; i++) cout " s2:" s2.pop()
"\n";
return 0;

2. ^include <iostream>
using namespace std;
union swapbytes {
unsigned char [2];
unsigned i;

swapbytes(unsigned x ) ;

494 _

__

C++

void swp() ;

)!

swapbytes : : swapbytes {unsigned x}


{
i = x;
I

void swapbytes: :swp(}


{
unsigned char temp;
temp = c[0};
c[0] = c[l];
c[l] = temp;
}

int main()
{

swapbytes ob(l) ;
ob . swp ( } ;
cout ob.i;
return 0;

3. ,
. , . , .

2.6
#include <iostream>
using namespace std;
// abs()
// abs()
inline int abs{int n}
1

cout " abs int\n";


return n<0 ? -n: n;
}

// abs{)
inline long abs(long n)

495

{
cout " abs{) long\n";
. return n<0 ? -n: n;
// abs { )
inline double abs (double n)
i
cout " abs() double \n";
return n<0 ? -n: n;
int main()
cout " -10:" abs (-10) "\n";
cout " -10L:" abs(-lOL) "\n";
cout " -10.01:" abs(-lO.Ol) "\n
return 0;

2. , for. .

2.7
1. ^include <iostrearn>
using namespace std;
ttdefine SI2E 10
// stack
class stack {
char stck[SIZE]; //
int tos; //
public:
stack () { tos = 0; }
void push(char ch)
{
if (tos==SIZE) {
cout " ";
return;

}
stck[tos]=ch;
tos-t-t-;

496

C++

char pop ( }
i
if (tos==0) {
cout " ";
return 0; // -

tos ;
return stck[tos];

int main ()
(
// , ,
stack si, s2;

int i;
si. push { 'a' ) ;
s2.push('x') ;
sl.push('b') ;
s2.push( 'y' ) ;
si. push ( 'c' ) ;
s2.push('2');
11

for(i=0; i<3; i++) cout " si:" sl.popO


\n";

for(i=0; i<3; i++) cout " s2 : " s2.pop()


"\n";
return 0;

2. #include <iostream>
^include <cstring>
ttinclude <cstdlib>
using namespace std;
class strtype {
char *p;
int len;
public:
strtype (char *ptr)
len = strlen(ptr);

p=(char *) mallocilen + 1) ;
if(!p} {
cout " \";
exit ( 1 ) ;

497

Strcpyfp, ptr);
~strtype() ( cout " p\n"; f (); }
void show()
cout p " : " len;
cout "\n";

int main()
strtype si (" "), 2{" C++"};
si. show () ;
s2. show () ;

return 0;

2
1. , .
, .
2. ^include <iostream>
using namespace std;
class line {
int len;
public:
line{int 1);
line::line(int 1)
{

len = 1;
int i;
for(i=0; i<len; i+4) cout '*';

}
int main()
line 1(10);
return 0;

C++

498

3. 1000000 -0.0009
4. ^include <iostream>
using namespace std;
class area_cl {
public:
double height;
double width;

class rectangle: public area_cl {


public:
rectangle (double h, double w) { height *= h; width = w; }
double area() { return height * width; }

class isosceles: public area_cl {


public :
isosceles (double h, double w) { height = h; width = w; }
double area() { return 0.5 * height * width; }

class cylinder: public area_cl {


public:
cylinder (double h, double w) { height = h; width = w; }
double area ()
-I
return (2 * 3.1416 * (width/2) * (width/2)) + (3.1415 *
height * width} ;

int
{

mainO
rectangle b ( 1 0 . 0 , 5 . 0 ) ;
isosceles i ( 4 . 0 , 6 . 0 ) ;
cylinder c ( 3 . 0 , 4 . 0 ) ;
cout ": " b . a r e a f ) "\n
cout ": " i . a r e a f ) "\n";
cout ": " c . a r e a ( ) "\n";
return 0;

5. . ,
, ,

499

. , .
6. ^include <iostream>
using namespace std;
class myclass {
int i, j;
public:
myclass(int x, int y) { i = x; j = y; }

\.
I r

void show() { cout i " " j; }

int main{)
{
myclass count(2, 3);
count.show();
return 0;

7. . .
8. . .


1. ^include <iostream>
using namespace std;
class prompt (
int count;
public:
prompt{char *s] { cout s; cin count; }
-prompt();

prompt::-prompt(} {
int i, j;
for{i=0; i<count; i
cout '\a ' ;
for(j=0; j<32000; J4+); //

C++

500

int main ( }
prompt ob( " : ");
return 0;

2. #include <iostream>
using namespace std;
class ftoi {
double feet;
double inches;
public :
ftoi {double f ) ;

);

ftoi: : ftoi (double f)


feet = f;
inches = feet * 12;
cout feet " " inches ". \n";
int main()
ftoi a (12.0) , b(99.0) ;
return 0;

3. ^include <iostream>
^include <cstdlib>
using namespace std;
class dice {
int val;
public:
void roll {) ;
);
void dice: :roll ()
{
val = (rand() % 6) +1; // 1 6
cout val "\n";
int main
{
dice one, two;

507

one.roll();
two.roll();
one.roll ( ) ;
two.roll () ;
one.roll () ;
two.roll { ) ;
return 0;

3

1. widgit(), - ~widgit().
2. (. .,
). .
3. class Mars: public planet {

4. , inline, .
5. . . .
goto switch. , .
6. sample ob(100, ' X ' ) ;

3.1
1. = , ell !2
, .
2. #include <iostream>
using namespace std;
#<3efine SIZE 100

502

class q_type {
. int queue [SIZE]; //
int head, tail; //
public:
q_type(); //
void q(int num) ; //
int deq(); //

};
//
q_type: :q_type{)
{
head - tail = 0;
}
//
void q_type : : q ( int num)
if (tail -I- l==head || (tail + 1SIZE SS Ihead)} {
cout " ";
return;
}

tail--;
if (tail==SIZE) tail = 0; //
queue [tail] = num;
//
int q_type: :deq()
if (head==tail) {
cout " ";
return 0;
head++;
if (head==SIZE) head = 0; //
return queue[head];
int main{)
q_type ql, q2;
int i;
for(i=l; i<=10; i++) {
ql.q(i);
}
//
q2 = ql;

C++

// ,
//
for(i=l; i<=10; i--)
cout " 1: " ql . deq ( ) "\n";
for(i=l; i<=10; i++)

cout " 2: " q2.deq() "\n";


return 0;

3. , ,
, , ,
, ,
, , . , .

3.2
1. ^include <iostream>
using namespace std;
ttdefine SIZE 10

// stack
class stack {
char stck[SIZE]; //
int tos; //
public:
stack (}; //
void push (char ch) ; //
char pop (); //
};
//
stack: :stack ()
{
cout " \" ;
tos = 0;
/ /
void stack: :push (char ch)
{
if (tos==SIZE) {
cout " \";
return;

504

C++

s t c k f t o s ] = ch;
tos-n-;
'

//
char stack::pop()
if (tos=0) {
cout " \";
return 0; //
tos;
return stck[tos];
void showstack{stack o) ;
int main()
\
stack si;
int i;
si.push('a'};
sl.push('b');
sl.push('c');
showstack(sl);
// si main{) -
cout " si : \";
for(i=0; i<3; i--) cout sl.popO "\n";
return 0;
//
void showstack(stack o)
char c;
// ,
//

while(=.()} cout "\";


cout "\";

505

si :

2, , ,
neg(), ,
neg() ;
mainO

3.3
1. ^include <iostreaici>
using namespace std;
class who {
char name;
public:
who(char c) {
name = c;
cout " who tt";
cout name "\n";
~who() { cout " who #" name "\n"; }
who rnakewho ()
f
who temp('') ;
return temp;
int main()
who ob('A');
makewho();
return 0;

2. , . : , ,
, ,
.

C++

506

3.4
1. ^include <iostream>
using namespace std;
class pr2; //
class prl {
int printing;

public:
prl() { printing = 0; }
void set_print(int status) { printing = status; }
friend int inuse{prl ol, pr2 o2);

class pr2 {
int printing;
//...
public:
pr2() { printing = 0 ; }
void set__print (int status) { printing = status; }
//...
friend int inuse{prl ol, pr2 o2);

//
int inuse(prl ol, pr2 o2)
{
if(ol.printing I I o2,printing) return 1;
else return 0;
int main(}

prl pi;
pr2P2;
if(linuse(pi, p2)) cout " \";
cout " pi ..An";
pl.set_print (1);
if(inuse(pl, p2)) cout " \"
cout " ! ... \";
pl.setjprint(0);
if (linuse{pi, p2)) cout " \";

. ___

507

cout " 2 . . . \";


p2.set_print(l);
if{inuse{pl, p2)) cout " \";
return 0;

3
1. , , .
2. obi 2 , ,
2, ,
. , , , , obi,
, .
3. int light (planet p)
{
return p.getjnilesU / 186000;

4. .
5. //
^include <iostream>
using namespace std;
kiefine SIZE 27
// stack
class stack {
char stck[SIZE]; //
int tos; //
public:
stack (); //
void push (char ch) ; //
char (); //
\.
//
stack: : stack ()
{
cout " \";

C++

508
tos - 0;

/I
void stack: :push(char ch)
(
if (tos==SISE) {
cout " \";
return;

stckftos] = ch;
tos++;

//
char stack: :pop()
{
if (tos==0) {
cout " \";
return 0; //
1
tos ;
return stck[tos];

void showstack (stack o) ;


stack loadstackO;
int main()
t
stack si;
si = loadstackO ;
showstack (si) ;
return 0;
//
void showstack(stack )
{
char ;
// ,
while(c=o.pop(}) cout "\";
cout "\";

//
stack loadstackf)

509

stack t;
char ;
for ( = ' ' ; <= ' z ' ; ++ ) t . push ( ) ;
return t;

6.
, , . , .
7. , ,
, . ,
, , .


1. //
^include <iastream>
^include <cctype>
using namespace std;
^define SIZE 27
// stack
class stack {
char s t c k f S I Z E ] ; //
int tos; //
public:
s t a c k ( ) ; //
void push(char ch) ; //
char pop(); //

//
stack: : stack {}
{
cout " \
tos = 0;

//
void stack: : push (char ch)

510

if (tos SIZE) {
cout " \";
return;
}
stck[tos] = ch;
tos++;
}

//
char stack: :pop()
{
if (tos0) {
cout " \";
return 0; //
tee i
return stckftos];

void showstack (stack o) ;


stack loads t ack ();
stack loadstack(int upper);
int rnainO
{
stack si, s2, s3;
si = loadstackO ;
showstack (si) ;
,,
//
s2 = loadstack(l) ;
showstack (s2) ;

//
s3 = loadstack(O) ;
showstack (s3} ;
return 0;
//
void showstack (stack )
{
char ;
// ,
while (c=o. pop (}) cout "\";

511

cout "\";
//
stack loadstack()
{
stack t;
char ;
for(c='a'; c<='z'; ++) t.push(c)
return t;

/* . ,
upper 1,
*/
stack loadstack{int upper)
(
stack t;
char c;
if (upper) = 'A' ;
else = 'a' ;
for (; toupper (c}<='Z' ; ++) t .push (c) ;
return t;

2. ^include <iostream>
^include <cstring>
^include <cstdlib>
using namespace std;
class strtype (
char *p;
int len;
public:
strtype (char *ptr) ;
-strtype ();
void show ( ) ;
friend char *get_string( strtype *ob) ;
};
strtype: : strtype (char *ptr)
(
len=strlen(ptr) ;
p=(char *) malloc(len+l) ;

512

__

______

C++

cout " \";


exit(l) ;

}
strcpyfp, ptr);
strtype : : -strtype ( )
{
cout " \";
free (p) ;
}
void strtype: : show ()
{
cout p " - : " len;
cout "\n";
}
char *get_string (strtype *ob)
f
return ob->p;
}
int main!)
{
strtype si (" -');
char *s;
si . show ( ) ;
//
s = get_string(sl) ;
cout " , si: ";
cout s "\n";
return 0 ;

3. : ,
, .
.
#include <iostream>
using namespace std;
class base {
int a;
public:

513

void load_a(int n) { = n; }
int get_a() { return a; }

};
class derived: public base {
int b;
public:
void load_b (int n) { b = n; }
int get_b() { return b; }
int main()
derived obi, ob2;
obl.load_a(5);
obl.load_b(10};
// obi 2
ob2 = obi;
cout " b obi: ";
cout obl.get_a() ' ' obl.get_b() "\n";
cout " b 2: ";
cout ob2.get_a() ' ' ob2.get_b() "\n";
/* , , ,

*/
return 0;

4

1. ,
, , ,
.
2. , ,
, . , , ,
.

++_

574

3. , .
. , , .
4. . , ,
. , -, , .
5. #include <iostream>
using namespace std;

class summation {
int num;
long sum; // num
public:

void set_sum(int n) ;
void show_sum{) {
cout " " num " " sum "\n";

void summation: :set_sum(int n)


{
int i;

num = n;
sura = 0;
for(i=l; i<=n;
sum += i;

summation make_sum()
{
int i;
summation temp;
cout " :

cin i;
temp. set_sum(i) ;
return temp;

int main ( }
{
summation s;

515

s = make_sum() ;
s .show_sura{) ;
return 0;

6. ,
.
7. tinclude <iostream>
using namespace std;
class myclass {
int num;
public:
myclass (int x) { num = x; }

friend int isneg (myclass ob) ;


int isneg (myclass ob)
{
return (ob.num < 0) ? 1: 0;
}
int main( )
{
myclass a(-l), b(2);
cout isneg(a) ' ' isneg(b);
cout "\n";
return 0;

8. ,
.

4.1
1. #include <iostream>
using namespace std;
class letters (
char ch;

516

public:
letters (char ) { ch = ; }
char get_ch() ( return ch; }

int main { )

{
letters ob [10] = { 'a', 'b', 'c1, 'd', '&',
f, 'g1, 'h', 'i', 'j' };

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

cout ob[ i ].get_ch() ' ';


cout "\n";
return 0;

2. ^include <iostrearti>
using namespace std;
class squares {
int num, sqr;
public :
squares {int a, int b) { num = a; sqr = b; }

void show() {cout num ' ' sqr "\n"; }


!i

int main ()
{
squares ob[10] = {

squares (1, 1) ,
squares (2, 4) ,
squares (3, 9) ,
squares (4, 16) ,
squares (5, 25) ,
squares (6, 36} ,
squares (7, 49) ,
squares (8, 64) ,
squares (9, 81) ,
squares (10, 100} ,

};
int i;
for{i=0; i<10; i++) ob [ i ] . show ( ) ;
return 0;

C++

3. ttinclude <iostream>
using namespace std;
class letters {
char ch;
public:
letters (char c) { ch = c; }
char get_ch() ( return ch; )
int main{)
{
letters ob[10] = {
letters ( 'a' ) ,
1
letters {'b ) ,
letters ('c') ,
letters ('d') ,
1
letters ( 'e ) ,
letters Cf) ,
letters ('g') ,
r
letters{'h ) ,
1
letters ( ' i ) ,
letters (' j M
};

int i;
for(i=0; i<10; i++)
cout ob [ i ] . get_ch ( }
cout "\n";
return 0 ;

4.2
1. //
^include <iostream>
using namespace std;
class samp {
int a, b;
public:
sarap{int n, int m) { a = n; b = m; }
int get_a{) { return a; }
int get_b{) { return b; }

517

C++

518

int main{)
samp ob[4] = (
samp (1, 2),

samp (3, 4),


samp(5, 6),
samp(1, 8)
int i;

sarnp *p;
p = &ob[3]; //
for(i=0; i<4

cout p -> get_a() ' ';


cout p -> get_b!) "\n";
p ; //
cout "\n";
return 0 ;

2. /*

*/
#include <iostream>

using namespace std;


class samp {
int a;
public:
samp (int n) { a = n; }

int get_a ( ) { return a; }


int main { )

samp ob [4] [2] = {


1, 2,
3, 4,
5, 6,
int i;

samp *p;

= (samp *) ob;
for(i=0; i<4; i
cout p->get_a ( } ' ' ;
P++;
cout p->get_a() "\n";
P++;

}
cout "\n";
return 0;

4.3
1. // this
#include <iostream>
using namespace std;
class niyclass {
int a, b;
public:
myclass(int n, int m) { this->a = n; this->b = m; }
int add() { return this->a + this->b; }
void showf) ;

};
void myclass::show()

(
int t;
t = this->add(); // -
cout t <<"\n";

}
int main()
{
myclass ob(10, 14);
ob.show();
return 0;

519

520

C++

4.4
1. ttinclude <iostream>
using namespace std;
int main{)
{
float *f;
long *1;
char *c;
f = new float;
1 = new long;
= new char;

if (!f I I !1 I I !c) {
cout " .
return 1;
}
*f = 10.102;
*1 = 100000;
*c = 'A';
cout *f ' ' *1 ' ' *c;
cout '\n';
delete f; delete 1; delete c;
return 0;

2. ^include <iostream>
^include <cstring>
using namespace std;
class phone {
char name[40];
char number[14];
public:
void store(char *n, char *mm) ;
void show{) ;
void phone::store(char *n, char *num)
strcpy(name, n);
strcpy (number, mm) ;

521

void phone: : show ( )


{
cout name ": " number,cout "\n";
)
int

rnain{)

phone *p;

p = new phone;
if(!p) (
cout " .";
return 1;
}

p->store( " ", "111 555-2323");


p->show ( ) ;
delete p;
return 0;

3. , new
, .
, , . C++, new
.

4.5
1. char *p;

p = new char[100] ;
// ....
strcpy(p, " "};
2. ^include <iostream>
using namespace std;

int main()
<
double *p;
.p = new double(-123.0987);

522

C++
cout * '\n';
return 0;

4.6
1. ^include <iostream>
using namespace std;
void rneg(int &i); //
void pnegfint *i); //
int main (}
{
int i = 10;
int j = 20;

rneg(i);
pneg(sj);
cout i ' ' j '\n';
return 0;
// -
void rneg(int si)

// -
void pneg(int *i)
*i = -*i;

2. tripleQ d , &.
. &.
3. - . .
, .
, .

523

4.7
1. show() . . showQ ,
. , , show(). , , , :
//
^include <iostream>
^include <cstring>
#include <cstdlib>
using namespace atd;
class strtype {
char *p;
public:
strtype(char *s) ;
~strtype() { delete [] p; }
char *get() ( return p; }
};
strtype::strtype(char *s)
int 1;

1 = strlen(s) + 1;
p = new char [1] ;
cout " \";
exit(l);
strcpy{p, s) ;
1

// -
void show(strtype sx)
{
char *s;
s = x.get () ;

cout s "\n";
int main()
{
strtype ("") , b ("") ;

524

C++
show(a);
show(b) ;
return 0;

4.8
1. //
^include <iostream>
ttinclude <cstdlib>
using namespace std;
class array (
int isize, jsize;
int *p;
public :
array (int i, int j);
int&put(int i, int j);
int get (int i, int j);
};
array: : array (int i, int j)
{
p = new int [ i * j ] ;
if(!p) (
cout " ";
exit(l) ;
isize = i;
jsize = j;
i

//
int fiarray: :put (int i, int j)
| i>=isize I I j<0 I I j>=jsize) {
cout ", ! !! \n";
exit 1 ) i

}
return p[i * jsize + j]; // p[ i ]

//
int array: :get (int i, int j)
(
if(i<0 || i>=isize I I j<0 I I j>=jsize} {
cout ", ! ! !\n";
exit ( 1 ) ;

.
return p[i * jsize + j ] ; //

}
int main{)
{
array a {2, 3 ) ;
int i, j;
for(i=0; i<2; i++)
f o r ( j = 0 ; j<3; j++)
a.put(i, j ) = i + j ;
for(i=0; i<2; i-b+)
f o r ( j = 0 ; j<3; j++)
cout a . g e t ( i , j ) ' ';
//
a.put(10, 10};
return 0;

2. . .

4
1. ^include <io5tream>
using namespace std;
class a_type {
double a, b;
public:
a_type(double x, double y} (
a = x;
b = y;
}
void show() ( cout a ' ' b "\n"; }
I;
int main()
{

a_type ob[2][5] = {
a_type(l, 1), a__type(2, 2 ) ,
a_type(3, 3 ) , a_type(4, 4 ) ,
a_type(5, 5), a_type(6, 6),
a_type{7, 7 ) , a_type(B, 8 ) ,
a_type(9 r 9 ) , a_type(10, 10}

525

526

C++

int i, j;
for(i=0; i<2;
for(j=0; j
ob[ i ][ j ],show();
cout r\n';
return 0;

2. #include <iostream>
using namespace std;
class a_type (
double a, b;
public:
a_type (double x, double y) {
a = x;
b = y;
void show{) { cout <:< a ' ' b "\n"; }

};
int mainO

,
\

a_type ob[2] [5] = {


a_type(l, 1), a_type(2, 2},
a__type(3, 3), a_type(4, 4),

a_type(5, 5), a_type(6, 6),


a_type(7, 7), a_type(8, 8),
a_type(9, 9), a_type(10, 10}

1;
a_type *p;
p = (a_type *) ob;

int i, j;
for(i=0; i<2
for(j=0; j<5;
p->ShOW ( ) ;

P++;
}
cout '\nr ;
return 0 ;

527

3. this , , .
4. new delete :
p-var new type;
delete p-var;
new .
,
sizeof. , <cstdlib>.
5.
.
- ,
.
6. ftinclu.de <iostream>
using namespace std;
void recip(double &d);
int main(}
double x = 100.0;
cout "x " x '\n';
recip (x);
cout " " x '\n';
return 0;
void recip (doubles &d)

d = 1/d;


1.
(->).
2, ^include <iostream>
#include <cstring>
ttinclude <cstdlib>
using namespace std;

528

C+

class strtype {
char *p;
int len;
public:
strtype(char *ptr);
-strtype();
void s h o w f ) ;
strtype:rstrtype(char *ptr)
len = strlen(ptr);
p = new char[len + 1];
cout " \";
exit(l) ;
strcpy(p, p t r ) ;
strtype::-strtype()
cout " \";
delete [] p;
void strtype::show()
cout << p " : " len;
cout "\n";
int main()
strtype si(" "), 2(" C++"
si.show();
s2.show();
return 0;

>

5

1. , . , ,

. ^

529

. :
, ,
, .
.
2. ^include <iostream>
using namespace std;
int

main()

{
float *f;
int *i;

f = new float;
i = new int;

i f ( i f I I !i) {
cout " \";
return 1;
*f = 10.101;
*i = 100;
cout *f ' ' *i ' \ n
delete f;
delete i;
return 0;

3. new, :
___ = new ({_) ;

, .
10:
int *p;
= new i n t ( 1 0 ) ;
4. ^include <iostream>
using namespace std;
class samp {
int x;
public:
samp (int n) { x = n; }

530

C++

int getxf) { return x; }

};
int raaint)
{
samp A[10] - { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } ;
int i;
for(i=0; i<10; i--)

cout A[ i ] . getx ( ) ' ';

cout "\n";
return 0;

5. :
. ,
. - , .
: - , - .

6. .
7. ^include <iostream>
using namespace std;
void mag (long snum, long order);
int main()

long n = 4 ;
long o = 2;
cout " 4, ";
mag (n, ) ;
cout n '\n' ;
return 0;

}
void mag (long snum, long order)
i
for(; order; order ) num = num * 10;

. ^

53?

5-1
1. ^include <iostream>
^include <cstring>
^include <cstdlib>
using namespace std;
class strtype {
char *p;
int len;
public:
strtype();
strtypefchar *s, int 1);
char *getstring() { return p; }
int getlengthO { return len; }
};
strtype::strtype(}
{
p = new char[255];
if(!p> {
cout " \";
exit(l);
}
*p = '\0'; //
len = 255;

}
strtype::strtype(char *s, int 1)
{
if(strlen(s) >= 1) {
cout " !\";
exit (1);
}
p = new char[ 1 ];
if(!p) {
cout " \";
exit(l) ;
}
strcpy(p, s);
len = 1;
)
int main ()

.
i

532

C++

strtype si;
strtype 2{" ", 100);
cout " si: " si.getstring () "- : "
cout sl.getlengthf) "\n";
cout " s2: " s2.getstring{) "- : "
cout s2.getlength(J "\n";
return 0;

2. //
^include <iostream>
^include <ctime>
using namespace std;
class stopwatch {
double begin, end;
public:
stopwatch () ;
stopwatch (clock_t t)
-stopwatch () ;
void start () ;
void stop () ;
void show() ;
stopwatch: :stopwatch(}
{
begin = end = 0.0;

stopwatch: : stopwatch (clock_t t)

i
begin = (double) t / CLOCKS_PER_SEC;
end = 0.0;
stopwatch: :~stopwatch()

!
cout " stopwatch .,.";
show ( ) ;

i
void stopwatch: : start ()

{
begin = (double) clockf) / CLOCKS_PER_SEC;

533

void stopwatch::stop ()
end - (double) clock / CLOCKS_PER_SEC;

void stopwatch::show()
cout " : " end begin;
-cout "\n";

int main()
stopwatch watch;
long i;
watch.start();
for{i=0; i<3200000; i+4-) ; //

watch.stop(};
watch.show();
//
stopwatch s2(clock{));
for{i=0; i<250000; 1--) ; //
s2.stop() ;

s2 . show () ;
return 0;
}

5.2
1. obj temp . ,
temp f{),
, .
# include <iostream>
using namespace std;
class myclass {
public:
myclass () ;

myclass (const myclass So) ;


myclass f () ;
II

534

C++

myclass: :myclass ()
{

cout " \" ;

}
//
myclass: irnyclass (const myclass So)
{
cout " \";

}
//
myclass myclass: :f()
{
myclass temp;
return temp;

'
int main ( )
{
myclass ob j ;
obj=obj . f () ;
return 0 ;

2. , getvalQ,
. getval()
, ( ) . -
,
getvalQ. .
.
//
#include <iostream>
^include <cstdlib>
using namespace std;
class myclass {
int *p ;
public:
myclass (int i) ;
myclass (const myclass s o ) ; //
~myclass() (delete p ; }
friend int getval (myclass o) ;

_ 535

rnyclass: :myclass (int i)

p=new int;

cout <:< " \";


exit(l) ;
}
*p=i;

}
1 1
myclass: irnyclass (const myclass & o )
f

p=new int;

//

if(!p) {
cout " \";
exit(l) ;
}
*=*.;

}
int getval (myclass )
t
return *o.p; //

}
int main()

{
myclass a(l) , b(2) ;
cout getval (a) " " getval (b) ;
cout "\n";
cout getval (a) " " getval (b) ;
return 0;

3. , . , .

5.4
1. ^include <iostream>
#include <cstdlib>

536

C++

using namespace std;


long mystrtol(const char *s, char **end, int base = 10)
return strtol(s, end, base);
int main ()
long x;
char *sl - "100234";
char *p;
x = mystrtol{si, &p, 16);
cout " 16: " x p\n';
x - mystrtol(si, &p, 10);
cout " 10: " x '\.';
x = mystrtol(si, 5p); // ,
//
cout " 10: "
'\';
return 0;

2. , , , . , ,
. ,
q .
3.
,
. Borland C++.
/* Borland C++
*/
#include <iostream>
^include <conio.h>
using namespace std;
void rnyclreol (int len = -1) ;
int main()
f
int i;

537

gotoxy(1, 1) ;
for(i=0; i<24; i++)
cout "abcdefghijklmnopqrstuvwxyzl23456789Q\n";
gotoxyd, 2) ;
inyclreol () ;
gotoxyd, 4) ;
myclreol{20) ;
return 0;
I
// , len
void inyclreol (int len}
{
int x, ;
x = wherex(); //
= whereyi); //
if(len == -1) len = 80 - x;

int i = x;
for(; i<=len; i++) cout ' ';
gotoxy(x, y); //

4.
.

5.6
1. ^include <iostream>
using namespace std;
int dif(int a, int b)
{
return a b;
}
float dif(float a, float b)
{
return a b;
)
int main f)
{
int (*pl)(int, int};

535

C++
float (*2) (float, float);
pi = dif; // diffint, int)
p2 = dif; // dif(float, float)
cout pi (10, 5) ' ';
cout p2!10.5, 8.9} '\n';
return 0;

5
1. // date() time_t
^include <iostream>
^include <cstdio> // sscanffi
^include <ctime>
using namespace std;
class date {
int day, month, year;
public:
date (char *str) ;
date (int m, int d, int y) {
day = d;
month = m;
year = y;
}
// time_t
date{time_t t) ;
void show() {
cout month '/' day '/';
cout year '\n';

date: : date (char *str)


{
sscanf (str, "%d%*c%d%*c%d", fimonth, &day, &year)
}
date: :date (time_t t)
{
struct tm *p;
p = localtirne ( f i t ) ;
day = p -> tm_mday;
month = p -> trn mon;

^.

__

__

__

539

year = -> tm_year;

}
int main()
{
//
date sdate("ll/l/92") ;
//
date idate(ll, I, 92) ;
/* time_t,
,

V
date tdate (time (NULL) ) ;
sdate. show() ;
idate. show() ;
tdate. show() ;
return 0;

2. samp . samp . ( samp x .)


3. ,
, . , , . .
4. :
(const ^) {

5. , , : ,
, .
6. overload . C++
, . .

540

__

C++

7. ,
,
.
8. ^include <iostream>
^include <cstring>
using namespace std;
void reverse (char *str, int count = 0 ) ;
int main ( )
{

char *sl = " ";


char *s2 = " C++";
reverse (si); //
reverse (s2, 7); //
cout si '\n';
cout s2 '\n' ;
return 0;
void reverse (char *str, int count)
{
int i, j;

char temp;
i f f l c o u n t ) count = s t r l e n ( s t r ) 1;
f o r ( i = 0 , j=count; i<j .

temp = str[ i ];
str[ i ] = s t r [ j ] ;

str[ j ] - temp;
}

9. , ,
, .
10. , , - .
11. , ,
compute() .
divisor, ?

541

12. , .
, , .


1. #include <iostream>
using namespace std;
void order{int &a, int fib)

{
int t;
if (a<b) return;
else { // b
t = a;
a = b;
b = t;

int main()
{
int x = 10, = 5;
cout "x: " x ", y: " ' \n ' ;
order {x, y) ;
cout "x: " x : ", y: " ' \n ' ;
return 0;

2. , , , .
3. , , , . ,
int f (int a, int b = 0) ;

:
int f (int a) ;
int f (int a, int b) ;

542

++

4. ^include <iostream>
using namespace std;
class samp {
int a;
public:
samp{) { a = 0; }
samp(int n) { a = n; }
int get_a() { return a; }

};
int
{

main()
samp ob ( 8 8 ) ;

samp obarray[10];

5. , . , -
.


1. class myclass {
int x, ;
public:
myclass (int i, int j) ( x = i; = j; }
myclass!) { x = 0; = 0; }

2. class myclass {
int x, y;
public:
myclass (int i = 0, int j = 0) { x = i; = j; }

3.
.

543

4. , , , . ( .)
5. , ,
. , .
6. , .
, .
7. ,
.
: , ,

.

6.2
1. // * / coord
^include <iostream>
using namespace std;
class coord {
int x, ; //
public:
coord!) { x = 0; y- 0; }
coord (int i, int j) { x = i; = j; }
void get_xy{int &i, int & j ) { i = x; j = y; }
coord operator* (coord o b 2 ) ;
coord operator/ (coord ob2);
// * coord
coord coord: : operator* (coord ob2)
(
coord temp;
temp.x = x * ob2.x;
temp. = * ob2.y;
return temp;

544

C++

1 1 / coord
coord coord: : operator/ (coord ob2)
{
coord temp;
*
temp.x = x / ob2.x;
temp. = / ob2.y;
return temp;
int main ()
coord ol (10, 10), o2(5, 3), o3;
int x, y;

o3 = ol * o2;
o3.get_xy(x, y) ;
cout "(ol * o2) X: " x ", Y: " "\n";
o3 = ol / o2;
o3.get_xy (x, y) ;
cout "(ol / o2) X: " x ", Y: " "\n";
return 0;

2. % ,
.

6.3
1. // < > coord
#include <iostream>
using namespace std;
class coord {
int x, ; //
public:
coord() ( x = 0; y= 0; }
coord(int i, int j) { x = i ; = j; }
void get_xy(int Si, int sj) { i = x; j = y; }
int operator<(coord ob2);
int operator>(coord ob2);
};
// < coord
int coord::operator<(coord ob2)

{
return <2. && <2.;

}
// > coord
int coord::operator>(coord ob2)
{
return x>ob2.x && y>ob2.y;
}
int main()
{
coord 01(10, 10), o2(5, 3) ;
if(ol>o2) cout "ol > o2\n";
else cout "ol <= o2\n";
if(ol<o2) cout "ol < o2\n";
else cout "ol >= o2\n";
return 0;

6.4
1. // -- coord
^include <iostream>
using namespace std;
class coord {
int x, ; //
public:
coord (} { x = 0; y= 0; }
coord int i, int j) { x = i; = j; }
void get_xy(int &i, int &j) { i = x; j = y; }
coord operator (}; //
coord operator (int notused) ; //

};
// coord
coord coord: : operator ()
{
--;

;
return *this;
II -- coord
coord coord: : operator (int notused}

545

C++

546

{
x;
;

return *this;
int main ( )
{
coord olUO, 10);
int x, y;
ol ; //
ol.get_xy (x, y) ;
cout " (ol } X: " x ", Y: " "\n";
ol; //
ol.get_xy {x, y) ;
cout "(~ol) X: " x ", Y: " "\n";
return 0;

2. // + coord
^include <iostream>
using namespace std;
class coord {
int x, ; //
public:
coord() { x = 0; y= 0; }
.coord{int i, int j) { x = i; = j; }
void get_xy(int Si, int Sj) { i = x; j = y; }
coord operator+(coord ob2); //
coord operators(); //
// + coord
coord coord::operator+(coord ob2)
coord temp;
temp.x = x + ob2.x;
temp. = + ob2.y;
return temp;
II + coord
coord coord::operator+

iftx<0)
if <y<0)

= -;
= -;

return *this;

int main ()
coord 01(10, 10), o2{-2, -2);
int , ;
01 = ol + o2; //
ol.get_xy (, ) ;
cout " (ol + o2) X: " x ", Y: " "\n";
02 = -2; //
o2 ,get_xy (, ) ;
cout "(+o2) X: " x ", Y: " "\n";

return 0;

6.5
1. /* / coord

V
^include <iostream>
using namespace std;
class coord (
int x, ; //
public:
coord() { x = 0; y= 0; }
coord(int i, int j) { x = i; = j; }
void get_xy(int si, int &j) { i = x; j = y; }
friend coord operator-(coord obi, coord ob2);
friend coord operator/(coord obi, coord ob2);

// coord
//
coord operator-(coord obi, coord ob2)
{
coord temp;
temp.x = obl.x ob2.x;

547

548

C++

temp. = obl.y - 2.;


return temp;
// / coord
//
coord operator/ (coord obi, coord ob2)
{
coord temp;
temp.x = obl.x / ob2.x;
temp. = obl.y / ob2.y;
return temp;
int main ( )
{
coord ol (10, 10), o2(5, 3), o3;
int x, y;

o3 = ol - o2;
o3.get_xy (x, y) ;
cout "(ol ~ o2) X: " x ", Y: " "\n";
o3 = ol / o2;
o3.get_xy{x, y) ;
cout "(ol / o2) X: " x ", Y: " "\n";

return 0;

2. // * ob*int int*ob
#include <iostream>
using namespace std;
class coord {
int x, ; //
public:
coord () { x = 0; y= 0; }
coord ( int i , int j ) { x = i ; = j ; }
void get_xy(int &i, int &j) { i = x,- j = y; }
friend coord operator* {coord obi, int i) ;
friend coord operator* (int i, coord ob2) ;
};
// *
coord operator* (coord obi, int i)

.
coord temp;
temp.x = . * i;
temp. = . * i;
return temp;
// *
coord operator* (int i, coord ob2)
{
coord temp;
temp.x = ob2.x * i;
temp . = ob2 . * i ;
return temp;
int main{)
{
coord ol(10, 10} , o2;
int x, y;
o2 = ol * 2; // ob * int
o2.get_xy (x, y} ;
cout "(ol * 2) X: " x ", Y: " "\n
o2 = 3 * ol; // int * ob
o2.get_xy (x, y) ;
cout "(3 * ol) X: " x ", Y: " "\n

return 0;

3. -, , , . - , ,
.
4. /* coord

*/
^include <iostream>
using namespace std;
class coord {
int x, ; //
public:
coordO { x = 0; = 0; }

550

coord (int i, int j) { x = i; = j; }


void get_xyfint Si, int &j) { i = x; j = y; }
//
friend coord operator [coord &ob) ;
//
friend coord operator (coord &ob, int notused) ;
};

// coord
//
coord operator (coord &ob)
(
ob.x ;
ob.y ;
return ob;
// coord
//
coord operator (coord &ob, int notused)
(
ob.x ;
ob.y ;

return ob;

int main()

i\

coord ol(10, 10) ;


int x, y;
ol ; / / ol
ol.get_xy (x, y) ;
cout "( ol) X: " x ", Y: " "\n";
ol ; // ol
ol.get_xy (x, y) ;
cout "(ol ) X: " x ", Y: " "\n";
return 0;

6.6
1. ^include <iostream>
#include <cstdlib>
using namespace std;

C++

class dynarray {
int *p;
int size;
public:
dynarray(int s);
int &put(int i);
int get(int i);
dynarray &operator=(dynarray Sob);

//
dynarray::dynarray(int s)
{
p = new int[s];
if(!p) {
cout " \
exit(l) ;

//
int sdynarray: :put {int i)
{
if (i<0 I I i>=size) (
cout " !\";
exit(l) ;

return p[i] ;

//
int dynarray: ; get (int i)
{
if (i<0 | | i>=size) (
cout " !\";
exit(l) ;

return p[i] ;

1
// = dynarray
dynarray fidynarray: :operator= (dynarray &ob)

{
int i;

55?

552

if (size! =ob. size) {


cout " ! \n";
exit(l);

for(i=0; i<size; i++) p[i] = ob.pfi];


return *this;
int main ()
{
int i;
dynarray obi (10) , ob2{10), ob3(100);
obl.put (3) - 10;
i = obl.get<3) ;
cout i "\n";

Ob2 = obi;
i = ob2.get(3) ;
cout i "\n";
//
obi = ; // ! !!
return 0;

6.7
1. ^include <iostream>
#include <cstring>
^include <cstdlib>
using namespace std;
class strtype {
char *p;
int len;
public:
strtype(char *s) ;
~strtype{) {
cout " "
(unsigned) p '\n
delete []p;
\

char *get() { return p; }


strtype &operator=(strtype &ob);

C++

char &operator[] (int i) ;

};
strtype: : strtype {char *s)
{

int 1;
1 - strlen(s) + 1;
p = new char [1] ;
if(!p) {
cout " ";
exit(l) ;

len = 1;
strcpytp, s) ;

}
(f
strtype sstrtype: :operator= (strtype sob)
t
//
if (len < ob.len) { //
//
delete [] p;
p = new char ~
if(!p) f
cout
^^ _^ .... i 11\";
exit(l);

len = ob.len;
strcpytp, ob.p);
return *this;

1 1
char sstrtype: :operator[] (int i)
{
if (i<0 I [ i>len-l) {
cout " ";
cout i "
exit(l) ;

return p[i];

553_

554

C++
int main()
{
strtype (""), b{"");
cout a.getO '\n';
cout b.getO '\n';
a = b; //
cout a. get {) 1 ;
cout b.getO '\n';
//
cout [0] [1] [2] "\";
//
[0] = 'X';
[1] = 'Y';
[2] = 'Z';
cout a.get() "\";
return 0;

2. ^include <iostream>
^include <cstdlib>
using namespace std;
class dynarray {
int *p;
int size;
public:
dynarray (int s} ;
dynarray &operator= (dynarray sob} ;
int soperator [ ] {int i) ;
//
dynarray: : dynarray {int s)
{

p = new int [s] ;


if(!p) (
cout " ";
exit(l);

size = s;

1.1 = dynarray
dynarray sdynarray: :operator= {dynarray sob)
{
int i;
if (size! =ob. size} {
cout " ! \n" ;
exit(l) ;

for(i=0; i<size; i++) p[i] = ob.p[i];


return *this;

1
// []
int Sdynarray: : operator [] (int i)
{
if (i<0 | | i>size) {
cout " ";
cout i " \";
exit(l) ;
}
return p[i] ;
int main{)
{
int i ;
dynarray obi(10), ob2(10}, ob3(100};
obl[3] = 10;
i = obi[3];

cout i "\n";
ob2 = obi;
i = ob2[3];
cout i "\n";
//
= ; //
return 0;

6
1. //

555

556

^include <iostream>
using namespace std;
class coord {
int x, ; //
public:
coord () { x - 0; = 0; }
coord (int i, int j) { x = i; = j; }
void get_xy(int si/ int &j) { i = x; j = y; )
coord operator (int i) ;
coord operator (int i);
//
coord coord: :operator (int i)
;
\

coord temp;
temp.x = x i;
temp. = i;
return temp;
//
coord coord: : operator (int i)
{
coord temp;
temp.x = x i;
temp. = i;
return temp;
int main ()
{
coord ol (4, 4) , o2;
int x, y;

o2 = ol 2; // ob int
o2.get_xy (x, y) ;
cout " (ol 2) X: " x ", Y: " "\n";
o2 = ol 2; // ob int
o2.get_xy (x, y) ;
cout " (ol 2) X: " x ", Y: " "\n";
return 0;

C++

2. tinclude <iostream>
using namespace std;
class three_d {
int x, y, z;
public:
three_d(int i, int j , int k)
{

x = i; y = j ; z = k;
}
three__d() { x = 0; = 0; z = 0; }
void getfint &i, int &j, int &k)
(

i = x; j = y; k = z;
}
three_d operator+ (three_d ob2);
three_d operator- (three_d ob2) ;
three_d operator++ ( ) ;
three_d operator ( ) ;
three_d three_d: :operator+ (three_d ob2)
1
three_d temp;
temp.x = x + ob2.x;
temp. = 4- ob2.y;
temp.z = z-t- ob2.z;
return temp;
three_d three_d: roperator- (three_d ob2)
{
three_d temp;
temp.x = x ob2.x;
temp. = ob2.y;
temp.z = z ob2.z;
return temp;
three_d three_d: :operator++
{
X4-+;

return *this;
}

557

555

C++

three__d three_d: : operator ( )


{

x ;

;
z ;
return *this;
}

int main()
{
three_d olUO, 10, 10), o2(2, 3, 4), o3
int x, y, z;

o3 = ol + o2;
-get (x, y, z) ;
cout " X: " x ", Y:
cout Z: " z "\n";
o3 = ol - o2;
o3.get(x, y, z) ;
cout " X: " x ", Y:

y;

y;

cout Z: " z "\n";


ol.get (x, y, z) ;
cout " X: " x ", Y: " y;

cout Z: " z "\n";


ol.get(x, y, z);
cout " X: " x ", Y: " y;

cout Z: " z "\n";


return 0;

3. #include <iostream>
using namespace std;
class three_d {
int x, y, z;
public:
three_d(int i, int j, int k)

x=i; y=j;
}
three_d() { x = 0

^ .
void get (int si, int &j, int &k)
i = x; j = y; k = z;

three_d operator+{three_d &ob2);


three_d operator-{three_d &ob2);
friend three_d operator++(three_d &ob) ;
friend three_d operator(three_d Sob);

three_d three_d::operator+(three_d &ob2)


three_jd temp/temp.x = x + ob2.x;
temp. = + ob2.y;
temp.z = z + ob2.z;
return temp;

three_d three_d::operator-(three_d sob2)


three_d temp;
temp.x = x ob2.x;
temp. = ob2.y;
temp.z = z ob2.z;
return temp;

three d operator++(three d Sob)

return ob;
}

three_d operator(three_d &ob}


{
ob.x;
ob.y;
ob. z ;
return ob;

559

560

C++

int ma in (}
{
three_d ol{10, 10, 10), o2(2, 3, 4), o3;
int x, y, z;

o3 = ol + o2;
o3.get(x, y, z);
cout " X: " x ", Y: " y;

cout Z: " z "\n";


03 = ol - o2;
o3.get(x, y, z) ;
cout " X: " x ", Y: " y;
cout Z: " z "\n";
o l . g e t ( x , y, z) ;
cout " X: " x ", Y: " y;
cout Z: " z "\n";
ol;

o l . g e t f x , y, z) ;
cout " X: " x ", Y: " y;
cout Z: " z "\n";
return 0;

4. - ,
this. - . -
. -
.
5. = , . , ,
.

6. .
7. ^include <iostream>
using namespace std;
class three_d {
int x, y, z;
public:
three d(int i,

int j,

int k)

^ _ 567

{
= i; y= j ; z = k;
}
three_d() { = 0; = 0; z = 0; }
void get (int si, int &j, int &k)
{
i = x; j = y; k = z;
}

friend three_d operator+ (three_d ob, int 1} ;


friend three_d operator^- (int i, three_d ob) ;
);

three_d operator+(three_d ob, int i)


(
three_d temp;
temp.x = ob.x + i;
temp. = ob.y + i;
temp. z = ob. z + i;
return temp;
I

three_d operator+ (int i, three_d ob)


{
three_d temp;
temp .x = ob . x + i ;
temp . = ob . + i ;
temp.z = ob.z + i;
return temp;
int main ( )
i
thread ol(10, 10, 10) ;
int x, y, z;
ol = ol + 10;

ol.getfx, y, z) ;
cout " X: " x ", Y: " y;
cout Z: " z "\n";

ol = -20 + ol;
ol.get (x, y, z) ;
cout " X: " x ", Y: " y;
cout 2,:. " z "\n";

return 0;

C++

562

8. #include <iostream>
using namespace std;
class three_d (
int x, y, z;
public:
three_d(int i, int j, int k)
{
x = i; = j ; z = k;
i
three_d() ( x = 0; = 0; z = 0; }
void get (int Si, int &j, int 5k)
(

i = x; j = y; k = z;
}
int operator== (three d ob2) ;
int operator !=(three_d ob2) ;
int operator I I (three_d ob2) ;

};
int three_d: : opera tor== (three_d ob2)
{
return x==ob2.x &s y==ob2 . && z==ob2.z;
}

int three_d: :operator!= (three_d ob2)


{
return x!=ob2.x SS y!=ob2.y s& z!=ob2.z;
}

int three_d: : operator! I (three_d ob2)


{
return x||ob2.x SS I I ob2 . 5& z||ob2.z;
}

int main ( )
{,

three_d ol(10, 10, 10), o2 (2, 3, 4), o3 (0, 0, 0)


if(ol==ol) cout "ol == ol\n";
if{ol!=o2) cout "ol !- o2\n";
if(o3||ol) cout "ol \
return 0;

563

9. [] ,

.


1. /*
.

V
#include <io5tream>
#include <cstring>
using namespace std;
class strtype (
char s[80];
public:
strtypeO { *s - '\0'; }
strtype(char *p) { strcpyfs, p); }
char *get{) { return s; }
strtype operator-t-(strtype s2) ;
strtype operator=(strtype s2) ;
int operator<(strtype s2);
int operator>(strtype s2);
int operator=={strtype s2);

strtype strtype::operator+(strtype s2)


{
strtype temp;
strcpy (ternp.s, s) ;
strcpy(temp.s, s2 .s);
return temp;

1
strtype strtype::operator=(strtype s2)
(
strcpy(s, s2.s);
return *this;

!
int strtype::operator<{strtype s2)
{
return strcmpfs, s2.s) < 0;

564

C++

int strtype::operator>(strtype s 2 )

{
return strcmpfs, s2.s) > 0;
}

int strtype::operator==(strtype s2)


,
return strcntp(s, s2.s) == 0;
}

int main ()
{
strtype ol(""), o2(" "), ;

o3 = ol + o2;
cout o3.get() "\n";
o3 = ol;
if(ol==o3) cout "ol o3\n";
if(ol>o2) cout "ol > o2\n";
if(ol<o2) cout "ol < o2\n";
return 0;

7

1. . ,
, .
2. .
C++.
3. , . ,
.
4. ^include <iostream>
using namespace std;
class array {
int nums[10];
public:
array {) ;

void set (int n[10] ) ;


void show () ;
array operator-f (array ob2) ;
array operator- (array ob2) ;
int operator== (array ob2) ;

};
array: r a r r a y ()
{
int i ;

f o r ( i = 0; i < 10; i++) nums [i] = 0;

void array: :set (int *n)


{
int i;
forfi = 0; i < 10; i++) numsfi] = n[i]

}
void array: : show ()
{
int i;
f o r d = Q; i < 10;
cout nums[i] ' ';
cout "\n";

}
array array: :operator+ (array ob2)
{
int i;
array temp;
for(i=0; i<10; i++} temp.nuras[i] = nurns[i] + ob2.nums[i];
return temp;

)
array array: : operator- (array ob2)
{
int i;
array temp;
for(i=0; i<10; i++) temp.numsfi] = nums[i] - ob2 . nurns [ i ] ;
return temp;

1
int array: :operator== (array ob2)

565

C++

566

{
int i ;

for(i=0; i<10; i++) if(nums[i] != ob2.nums[i]) return 0,return 1;

1
int main!)
i\
array ol, o2, o3;

int i[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };


ol.set (i);
o2.set (i);

o3 - ol + o2;
o3.show();
o3 = ol o3;
o3. show() ;
if(ol==o2) cout "ol o2\n";
else cout "ol 2\";
if(ol==} cout "ol o3\n";
else cout "ol \";
.return 0;

5. ^include <iostream>
using namespace std;
class array {
int nums[10];
public:
array () ;
void set(int n[10]);
void show();
friend array operator-*-(array obi, array ob2);
friend array operator-(array obi, array ob2);
friend int operator==(array obi, array ob2);
};
array: :array {)

int i;

f o r ( i = 0; i < 10; i++) n u m s f i ] = 0;

1
void array : :set (int *n)
t
int i;
f o r ( i = 0; i < 10; i++) nums[i] = n [ i ] ;

I
void array: :show()
{
int i;
f o r d = 0; i < 10; i++) cout nums[i] ' ';
cout "\n";
J

array operator+ (array obi, array ob2)


{
int i;
array temp;
for(i=0; i<10; i++) temp.nums[i] = obl.nums[i] + ob2.nums[i];
return temp;

}
array operator- (array obi, array ob2)
{
int i;
array temp;
for(i=0; i<10; i++) temp. nums [i] = obl.nums[i] ob2 . nums [ i ] ;
return temp;

1
int operator== (array obi, array ob2)
{
int i;
f o r ( i = 0 ; i<10; i++) if (obi .nums [i]
return 1;
}

int main{)
{
array ol, o2, o3;

!= o b 2 . n u m s [ i ] J return 0;

567

568

__

int i[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

ol.set (i) ;
o2.set (i) ;
o3 - ol + o2;
o3 . show ( } ;
03 - ol - o3;
o3 . show ( ) ;

if (ol==o2) cout "ol o2\n";


else cout "ol 2\";
if{ol==o3) cout "ol o3\n";
else cout "ol \";
return 0;

6. ttinclude <iostream>
using namespace std;
class array {

int nums [10] ;


public :
array ( ) ;
void set (int n[10]);
void show() ;
array operator++ () ;
friend array operator (array Sob) ;
};

array: : array ()
{
int i;
for(i = 0; i < 10; i++) nums[i] = 0

void array: :set (int *n)


{
int i;
for(i - 0; i < 10; i++) nums[i] = n[i]

void array :: show ()


f
int i;

569

for (i = 0; i < 10; i++)


cout nums[i] ' ';

cout "\n";
// -
array array: :operator++ f)
int i;

for{i=0; i<10; i++) nums[i]++;


return *this;
//
//
array operator (array &ob)
{
int i;
for{i=0; i<10; i+-f) ob.nums[i] ;
return ob;
}

int main()
{
array ol, o2, o3;

int i[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };


ol.set (i) ;
o2.set(i) ;

o3 = 4+o 1 ;
o3.show() ;
o3 = ol;
o3. show{) ;
return 0;

7. .
-.

++_

570

7-1
1. .
2. , .
, .

7.2
1. ,
.
,
.
2.
, , ,
.

3. .

7.3
1. ^include <iostream>
^include <cstring>
using namespace std;
class raybase {
char str[aO];
public:
mybase(char *s) { strcpy(str, s)
char *get() { return str; }

class myderived: public mybase {


int len;
public:
myderived{char *s}: mybase(s) {
len = strlen(s);
int getlenf) { return len; }
void show() { cout get() '\n'; }

};

. _
int main ()

{
myderived ob { " ");
ob . show ( ) ;
cout ob.getlenf) '\n';
return 0;

2. #include <iostream>
:sing namespace st
// -.
class vehicle {
int num_wheels;
int range ;
public:
vehicle {int w, int r)
num_wheels = w; range = r;

}
void showv ( )
{
cout " : " num wheels '\n'
-
cout ": " range ' \ n '

class car: public vehicle {


int passengers;
public:
car (int p, int w, int r) : vehicle (w, r)
{
passengers = p;
}
void show ( )
(
showv { ) ;
cout " : " passengers ' \n '

class truck: public vehicle (


int loadlimit;
public:
truck(int 1, int w, int r) : vehicle (w, r)

571

572

C++

{
loadlimit = 1;

void show { )

(
showv ( ) ;
cout ": " loadlimit ' \n ' ;

int main ()

{
car c(5, 4, 500) ;
truck t (30000, 12, 1200)
cout ": \n";
c.show() ;
cout ": \n";
t . show ( ) ;
return 0;

7.4
1.

2. ^include <io5tream>
using namespace std;
class A {
int i ;
public:

A (int a) { i - a; }
class {
int j ;
public:
B{int a) { j = a; }

573

class : public A, public {


int k;
public:
C{int , int b, int a ) : A ( a ) , B ( b ) {
k = c;

7.5
2. ,
( ) ,
.
( ) . , ,
.

7
1. ttinclude <iostream>
using namespace std;
class building {
protected;
int floors;
int rooms;
double footage;

class house: public building {


int bedrooms;
int bathrooms;
public:
house {int f, int r, double ft, int br, int bth)
floors = f; rooms = r; footage = f t ;
bedrooms = br; bathrooms = bth;
}
void show ( )
cout
cout
cout
cout
cout

{
":
":
":
":
": "

" floors ' \ n ' ;


" rooms ' \ n ' ;
" footage ' \ n ' ;
" bedrooms ' \n ' ;
bathrooms ' \ n ' ;

574

__

__

C++

class office: public building {


int phones;
int extinguishers;
public :
office (int f, int r, double ft, int p, int ext) (
floors = f; rooms = r; footage = ft;
phones = p; extinguishers = ext;
}
void showO (
cout ": " floors '\n';

cout ": " rooms '\n';


cout ": " footage ' \n' ;
cout ": " phones '\n';
cout : ": " extinguishers '\n';

int rnainO
I
house h_ob(2, 12, 5000, 6, 4);
office o_ob(4, 25, 12000, 30, 8) ;
cout " : \";
h_ob . show ( ) ;
cout ": \n";
o_ob.show() ;

return 0;

2. ,
, .
,
.
3. , (protected), , ( )
. protected
.
4. . .
5. ^include <iostream>
using namespace std;

. !

__

575

class planet (
protected:
double distance; //
int revolve;
//
public:
planet (double d, int r) { distance = d; revolve = r; }

class earth: public planet (


double circumference; //
public :
earth (double d, int r) : planet (d, r) {
circumference = 2 * distance * 3.1416;
}
void show() (
cout " : " distance '\n';
cout " : " revolve ' \n ' ;
cout " : " circumference '\n'

int main()
{
earth ob (93000000, 365);
ob . show ( ) ;
return 0;

6. , motorized road_use
vehicle .


1. switch
. "" .
2. , . .
, , = , ,
.

5/6

8

1. ^include <iostrearn>
using namespace std;
class airship {
,
protected:
int passegers;
double cargo;

class airplane: public airship {


char engine; // p , j
double range;
public:
airplane (int p, double c, char e, double r}
{
passegers = p;
cargo = c;
engine = e;
range = r;
}
void show ( ) ;

11

class balloon: public airship {


char gas; // h ,
double altitude;
public:
-balloon (int p, double c, char g, double a)

passegers = p;
cargo = c;
gas = g;
altitude = a;
}
void show f ) ;

void airplane: : show ()


{
cout " : " passegers '\n';
cout " : " cargo ' \n' ;
cout ": ";

C++

,
if (engine=='p' ) cout "\";
else cout "\";
cout ": " range '\n';
void balloon: : show ()
{
cout " : " passegers '\n'
cout ": " cargo '\n';
cout " : " ;
if(gas=='hM cout "\";
else cout "\";
cout ": " altitude '\n';
}

int. ma in ()
{
balloon (2, 500.0, 'h1, 12000.0);
airplane b727 (100, 40000.0, 'j', 40000.0);
b. s h o w ( ) ;
cout ' \ n ' ;
b727.show() ;

return 0;

2. protected ,
.
3.
.

4. ABC, .
5. #include <iostream>
using namespace std;
class base {
int i, j;
public:
base (int , int y) {i = x; j = y; }

575

-^___

__

C++

void showij (} { cout i ' ' j '\n'; }


class derived: public base {
int k;
public :
derived(int a, int b, int c) : base(b, c) (
k = a;
}
void showO { cout k ' '; showij {); }
h
int main{)
{
derived ob(l, 2, 3) ;
ob. show{) ;
return 0;

6. "" "".

8.2

"

1. Hnclude <iostream>
using namespace std;
'
int main()
<
cout .setf (ios: : showpos) ;
cout -10 ' ' 10 r\n';
return 0;
}

2. ^include <iostream>
using namespace std;
int main{)
{
cout. setf {ios: : showpoint | ios: : uppercase [ ios: : scientific) ;
cout 100.0;

.
return 0;

3. ^include <iostream>
using namespace std;
int main()
{
ios::fmtflags f;
f = cout.flags(); //
cout.unsetf(ios::dec);
cout,setf(ios::showbase | ios::hex);
cout 100 '\n';
cout-flags(f); //
return 0;

8.3
1. /*
2 100
*/
tfinclude <iostream>
^include <cmath>
using namespace std;

int main ()
double x;
cout,precision(5) ;
cout "x
Ig x

In x\n\n";

for(x = 2.0; x <= 100.0; x++) {


cout.width(10);
cout x " ";
cout.widthUO)/
cout loglOCx) " ";
cout.width(10);
cout log(x) "\n";
return 0;

579

580

^:++

2. ^include <iostream>
ttinclude <cstring>
using namespace std;
void center(char *s);
int mainf)
center(" !");
.center(" C++.");
return 0;
void center(char *s)
{
int len;
len = 40 + ( s t r l e n ( s } / 2 ) ;
cout.width(len);
cout "\n";

8.4
la.// 2 100
^include <iostream>
^include <iomanip>
ftinclude <cmath>
using namespace std;
int main()
double x;
cout setprecision(S);
cout "x
Ig x

In x\n\n";

for(x = 2.0; x <= 100.0; x++} {


cout setw(10} x " ";
cout setw(lO) loglO(x) " ";
cout setw(10} log(x) "\n";
return 0;

lb.^include <iostream>
^include <iomanip>

581

^include <cstring>
using namespace std;
void center(char *s);
int
t

main()
center(" ! " ) ;
cents(" C++.");
return 0;

void centerfchar *s)


int len;

len = 40 + (strlen(s)/2);
cout setw(len) s "\n";

}
2. cout setiosflags(ios:ishowbase I ios::hex) 100;
3. boolalpha ,
trae false.
boolalpha trae false.

8.5
1. ^include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class strtype {
char *p;
int

len;

public:
strtype(char *ptr);
-strtype() (delete [] p; }
friend ostream soperator(ostream &stream, strtype &ob);
strtype::strtype(char *ptr)
len = strlen(ptr) + 1;

582

___

= new char [len];


if(!p> (
cout " ";
exit(l);
}
strcpy(p, ptr} ;

ostream &operator {ostream &stream, strtype &ob)

{
stream ob.p;
return stream;

int main()

{
strtype si (" "), 2(" C++"};
cout si;
cout endl s2 endl;
return 0;

2. Hnclude <iostream>
using namespace std;
class planet {
protected:
double distance; //
int revolve;
//
public :
planet {double d, int r) { distance = d; revolve = r; )

class earth: public planet {


double circumference; //
public:
earth(double d, int r) : planetfd, r) (
circumference = 2 * distance * 3.1416;
1
friend ostream &operator (ostream sstream, earth sob) ;

};
ostream &operator (ostream ^stream, earth Sob)
{
stream " : " ob. distance '\n';

C++

533

stream " : " ob. revolve ' \ ' ;


stream " : " ob. circumference;
stream ' \n' ;
return stream;

int main()

(
earth ob(93000000,

365);

cout ob;
return 0;

3. - ,
, , .

8.6
1. tfinclude <iostream>
ttinclude <cstring>
^include <cstdlib>
using namespace std;
class strtype {
char *p;
int len;
public:
strtype(char *ptr);
-strtype 0 { delete [] p; }
friend ostream &operator [ostream sstream, strtype &ob)
friend istream soperator(istream fistream, strtype &ob)
};
strtype::strtype(char *ptr)
{
len = strlen(ptr)+l;
p = new char [len];
if(!p) {
cout " \";
exit(1);
strcpy(p, ptr);

584

C++

ostream &operator (ostream sstream, strtype sob)


stream ob.p;
return stream;
istream ^operator (istream sstream, strtype sob)
{
char temp[255J;
stream temp;
if(strlen(temp) >= ob.len) {
delete ob.p;
ob.len = strlen(temp) + 1;
ob.p = new char [ob.len];
if(!ob.p) {
cout " \";
exit(1);
}
1
strcpy(ob.p, temp);
return stream;

}
int main ()
f
strtype si(" "), 2(" C++")
cout si;

cout '\n' s2;


cout " : ";
cin si;
cout si;
return 0;

2. ^include <iostream>
using namespace std;
class factor j
int num;
//
int Ifact; //
public:
factor (int i);

.
friend ostream &operator (ostream ustream, factor ob) ;
friend istream ^operator (istream ustream, factor &ob) ;

factor: : factor (int i)


{
int n;
nura = i;
for(n=2;

if {! (i%n) } break;
if (ni/2) ) Ifact = n;
else Ifact = 1;

}
istream ^operator (istream sstream, factor Sob)
{
stream ob.num;

int n;
for{n=2; n<(ob.num/2) ; n+4}
if ( ! (ob.nurnfcn) ) break;
if (n<(ob.num/2) ) ob. Ifact = n;
else ob. Ifact = 1;
return stream;

I
ostream fioperator (ostream Sstream, factor ob}
{
stream ob. Ifact " "
stream ob.num '\n';
return stream;

}
int main ( )
{
factor o(32) ;
cout o;

cin o;
cout o;
return 0;

555

586

C++

8
1. tinclude <iostraam>
using namespace std;
int main()
{
cout 100 ' ' ;
cout.unsetf (ios: :dec) ; // dec
cout.setf {ios: :hex) ;
cout 100 ' ' ;
cout ,unsetf( ios: : hex) ; // hex
cout.setf (ios: :oct) ;
cout 100 '\n';
return 0;

2. ^include <iostream>
using namespace std;
int main ( )
I"

cout.setf (ios: :left) ;


cout.precision(2) ;
cout. fill ('*'},
cout.width(20) ;
cout 1000.5354 '\nr;
return 0;

. #include <iostream>
using namespace std;
int main()
{
cout 100 ' ';
cout hex 100 ' ';
cout oct 100 '\n';
return 0;

3b. #include <iostream>


^include <iomanip>
using namespace std;
int main()
(
cout
cout
cout
cout

setiosflags (ios: :left) ;


setprecision (2) ;
setfilK1*1} ;
setw(20) ;

cout 1000.5354 '\n';


return 0;

4. ios: : fmtf lags f;


f = cout. flags (); //

cout. flags ( ) ; //
5.
us?

ttinc"
->stream>
. HU!: "- std;

L t exponent;
double result;
public:
pwr(int b, int
friend ostream
friend istream
};

//
e);
&operator(ostream sstream, pwr ob);
fioperator (istream fistream, pwr &ob)

pwr::pwr(int b, int e)
{
base = b;
exponent = e;
result = 1;
for{; e; e ) result = result * base;
}

ostream &operator(ostream Sstream, pwr ob)


!
stream ob.base " " ob.exponent;
stream " " ob.result '\n';

587

C++

588
return stream;

istream ^operator (istream sstrearn, pwr sob)


(
int b, e;

'cout " :
stream fa e;
-.
pwr temp(b, e) ;
ob = temp;
return stream;
}

int main ( )
<

pwr ob(10, 2) ;

cout ob;
cin ob;
cout ob;
return 0;

6. //
#include <iostream>
using namespace std;
class box {
int len;
public:
box(int 1) { len - 1; }
friend ostream &operator (ostream ^stream, box ob) ;
//
ostream &operator (ostream &stream, box ob)
int i, j;

for{i=0; i<ob.len; i++) stream '*';


stream '\n';
for(i=0; i<ob.len-2; i++) {
stream '* ' ;
for(j=0; j<ob.len-2; j++) stream ' ';

.
stream "*\";
1
for{i=0; i<ob.len; i++) stream '*';
stream ' \n';
return stream;

}
int main()
{

box {4), 2(7) ;


cout endl b2;
return 0;


1. ^include <iostream>
using namespace std;
^define SIZE 10
// stack
class stack {
char stck[SIZE]; //
int tos; //
public:
stack () ;
void push (char ch) ; //
char pop(); //
friend ostream &operator (ostream sstream, stack ob) ;

};
//
stack: : stack ()
{
tos=0;

//
void stack: :push(char ch)
{
if (tos==SIZE) (
cout " ";
return;

589

590

stck[tos]=ch/
tos--;

}
//
char stack:: pop ()
{
if (tos==0) {
cout " ";
return 0; //
}
tOS--;
return stck[tos];
}
ostream &operator (ostream Sstream, stack ob)
{
char ch;
while (ch=ob.pop() } stream ch;
stream endl;
return stream;
int main ()

{
stack s;
s.pushf 'a') ;
s . push ( ' b ' ) ;
s.push ( 'c' ) ;
cout s;
cout s;
return 0;

2. ^include <iostream>
^include <ctime>
using namespace std;
class watch {
time_t t;
public:
watch {} ( t = time (NULL); }
friend ostream &operator {ostream Sstream, watch ob) ;

C++

,
ostream &operator (ostream &stream, watch ob)
{
struct tin *localt;
localt - localtime(sob.t);
stream asctime(localt) endl;
return stream;

}
int main ()
t
watch w;
cout w;
return 0;

3. #include <iostream>
using namespace std;
class ft_to_inches {
double feet;
double inches;
public:
void set (double f} {
feet = f;
inches = f * 12;
}
friend istream soperator (istrearn sstrearn, ft_to_inches Sob);
friend ostream &operator(ostream fistream, ft_to_inches ob);
};
istream separator{istream fistream, ft_to_inches iob)
1
double f;
cout " : ";
stream f;
ob.set(f);
return stream;

1
ostream &operator (ostream Sstrearn, ft_to_inches ob)

stream ob.feet " " ob.inches;


stream " \";

597

C++

592
return stream;

int main{)
ft_to__inches x;

cin x;
cout x;
return 0;

9

1. ^include <iostream>
using namespace std;
int main ()
{
cout.width(40);
cout. fillC : ') ;
cout "C++ " '\n';
return 0;

2. #iriclude <iostream>
using namespace std;
int main()
{
cout.precision(4};

cout 10.0/3.0 '\np;


return 0;

I
3. #include <iostream>
^include <iomanip>
using namespace std;
int main()
{
cout setprecision(4) 10.0/3.0 '\n';

593

return 0;

4. -
operator(), . - operator(),
.
5. ^include <iostream>
using namespace std;
class date {
char d[9]; // : mm/dd/yy
public:
friend ostream &operator (ostream sstream, date ob) ;
friend istream ^operator (istreara sstream, date &ob) ;
};
ostream &operator (ostream sstream, date ob)
{
stream ob.d '\n';
return stream;
istream ^operator (istream fistream, date fiob)
{
cout " (mm/dd/yy) : ";
stream ob.d;
return stream;
int mainO
{
date ob;

cin ob;
cout ob;
return 0;

6.
<iomanip>.
7. :
cin
cout
cere
clog

594

C++

9.1
1. //
^include <iostream>
tinclude <ctime>
using namespace std;
//
ostreara &td(ostream &stream)
{

struct tm *localt;
time_t t;
t = time(NULL);
localt = localtime(St);
stream asctime (localt) endl;
return stream;
}

int main{)
{
cout td '\n';
return 0;

2. ^include <iostream>
using namespace std;
// X
//
ostrearn &sethex (ostream Sstream)

i
stream.unsetf(ios::dec | ios::oct);
stream.setf(ios::hex I ios::uppercase | ios::showbase);
return stream;
}

//
ostream sreset(ostream fistream)
{
stream, unsetf (ios : :hex I ' - "- : uppercase I ios: : showbase) ;
stream.setf(ios::dec);
return stream;

int main ()
{
cout sethex 100 '\n';
cout reset 100 '\n';
return 0;

3. ^include <iostream>
using namespace std;
// 10
istream sskipchar(istream stream)

int i;
char c;
for{i=0; i<10; i++) stream c;
return stream;
int main()
char atr[80];
cout " : ";
cin skipchar str;
cout str '\n';
return 0;

9.2
1. //
ttinclude <iostream>
^include <fstream>
using namespace std;
int main{int argc, char *argv[ ])
t
if(argc!=3) {
cout " <_> <_>\";
return 1;
}
ifstream fin{argv[l]); //
ofstream fout(argv[2]); //

595

596

__

C++

if(!fin) (
cout " \";
return 1;
}

if (! fout) {
cout " ";
return 1;
>

char ch;
unsigned count = 0;
fin.unsetf (ios: :skipws) ; //
while (Ifin.eof 0 ) {

fin ch;
if (Ifin.eof () ) {
fout ch;
count++;

cout " : " count '\n';


fin. closed ;
fout .close {) ;
return 0;
, , ,
, . , / , .
, / .
2. ^include <iostream>
#include <fstream>
using namespace std;
int main (}

of stream pout ("phone") ;


ifUpout) {
cout " PHONE ";
return 1;

.
pout " , 415 555-3423\";
pout " , 213 555-2312\";
pout " , 202 555-1111\";

pout.close();
return 0;

3. //
^include <iostream>
^include <fstream>
^include <cctype>
using namespace std;
int main (int argc, char *argv[])
{
if(argc!=2) {
cout " : <_>\
return 1;

ifstream in(argv[ 1 ]);


cout " \"
return 1 ;

int count = 0;
char ch;
in ch; //
//
in.unsetf (ios: iskipws) ; //
while ( ! in.eof {) ) (
in ch;
if (isspace (ch) ) (
count++;
while {isspace (ch) && ! in.eof (}) in ch;

cout " : " count ' \n ' ;


in. close {};
return 0;

597

598

C++

__

( ,
. ,
. . .)
4. is_open , .

9.3
1. //
# include <iostream>
^include <fstream>
using namespace std;

int rnain(int argc, char *argv[])


if(argc!=3) {
cout ": <_> <__>\";
return 1;
}
ifstream fin(argv[l], ios::in I ios : :binary) ;

//

//
ofstrearn fout (argv[2] , ios::out | ios : :binary) ; //

//
if{!fin) (
cout " \n";

return 1;

iff! fout) {
cout " ";
return 1;

char ch;
unsigned count = 0;

while (Ifin.eof (} ) (
fin. get (ch) ;
if ( Ifin.eof {) }
fout. put (ch) ;
count++;

cout " : " count '\n';


fin. closed ;
fout .close () ;

return 0;

lb. //
#include <iostream>
#include <fstream>
^include <cctype>
using namespace std;
int main (int argc, char *argv[])
{
if (argc!=2) {
cout ": <_>\";
return 1;
)
if stream in{argv[l] , ios: :in | ios : : binary) ;
if('in) {
cout " \";
return 1;
}
int count 0;
char ch;
//
do {
in. get (ch) ;
} while (isspace (ch) } ;
while ( lin.eof (} } {
in. get (ch) ;
if (isspace (ch) ) {
count ++;
//
while (isspace (ch) && lin.eof () ) in. get (ch) ;

cout " : " count '\n';


in. close () ;
return 0;

2. // account
//
^include <iostream>

599

600

__

__

^include <fstream>
^include <cstring>
using namespace std;
class account {
int custnum;
char name[80] ;
double balance;
public :
account (int c, char *n, double b)
{
custnum = c;
strcpy(name, n) ;
balance = b;
}
friend ostream &operator (ostream sstream, account ob) ;
>'
ostream &operator {ostream Sstream, account ob)
t
stream ob. custnum ' ';
stream ob.name ' ' ob. balance;
stream '\n' ;
return stream;
int main ( )
{
account RexflOll, "Ralph Rex", 12323.34);

ofstream out ("accounts", ios::out I ios: :binary) ;


if (lout) f
cout " "
return 1;

}
out Rex;
out .close {) ;
return 0;

9.4
1. // get()
^include <iostream>
^include <fstream>
using namespace std;

C++

601

int main()
char str [80];
cout " : ";
cin.get (str, 79);
cout str ' \ n ' ;
return 0;
, , get() getlineO
2. // getlineO
ttinclude <iostream>
^include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
if{argc!=2) {
cout ": <__>\";
return 1;
ifstreara in(argv[l]);
cout " ";
return 1;
char str[255];
while(lin.eof()) {
in.getline(str, 254);
cout str '\n';
J
in.closeO ;
return 0;
I

9.5
1. //
^include <iostream>
^include <fstream>
using namespace std;

602

__

int main(int argc, char *argv[])


{
if(argc!=2) {

cout ": <_>\";


return 1;

}
if stream in (argv [ 1 ] , ios : : in I ios : : binary) ;
if(!in) {
cout " \";
return 1;
char ch;
long i;
// ( eof)
in.seekg(0, ios::end);
i = (long) in.tellgO; //
i

4-

=s ,
9 f

for(; i>=0; i~) {


in.seekg(i, ios::beg);
in.get(ch);
cout <<; ch;
in. close {) ;
return 0;

2. //
^include <iostream>
ttinclude <fstream>
using namespace std;
int main(int argc, char *argv[])
{
if(argc!=2) {
cout ": <_>\";
return 1;

// /
f stream io(argv[ 1 ] , ios; :in 1 ios : :out | ios: : binary) ;
cout " \";

C++

.
return 1;

}
char chl, ch2;
long i;
for(i=0; !io.eof(); i+=2) {
io.seekg (i, ios::beg);
io.get(chl);
if(io.eof()) continue;
io.get(ch2);
if(io.eof()) continue;
io.seekg(i, ios::beg);
io.put(ch2);
io.put(chl);
}
io.close (};
return 0;

9.6
la./*

*/
^include <iostream>
^include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
if (argc!=2) (
cout ": <_>\";
return 1 ;

if stream in (argv [ 1 ] , ios : : in | ios : : binary) ;


if(!in) f
cout " \" ;
return 1 ;
char ch;
long i;
// ( eof)
in. seekg(0, ios: :end) ;

603

604

if { ! i n . g o o d ( ) } return 1;

i = (long) in.tellgO; //
if ( ! in. good ) return 1;
i -= 2;
for(; i>=0; i } {
in.seekg (i, ios : :beg) ;
if ( ! in. good () ) return 1;
in. get (chj ;
if { ! in. good {) ) return 1;
cout ch;
in. close () ;
if ( ! in. good{) } return 1;
return 0;

1. //
ftinclude <iostream>
^include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
. if (argc!=2) {

cout ": <_>\";


return 1 ;
// /
f stream io (argv [ 1 ] , ios : : in | ios : : out i ios : : binary) ;
if(!io) {

cout " \";


return 1;
char chl, ch2;
long i;
for(i=0; !io.eof(); i+=2) {
io.seekg (i, ios: :beg) ;
if ( !io.good(} ) return 1;
io.get (chl) ;
if (io.eof () ) continue;
io.get (ch2) ;
if ( ! io. good ( ) ) return 1;

C++

if (io.eof {) ) continue;
io.seekg (i, ios: :beg) ;
if ( !io.good() ) return 1;
io.put (ch2) ;
if { ! io. good () } return 1;

io.put (chl) ;
if ( lio.goodf) ) return 1;
io. close () ;
if ( ! io.good () ) return 1;
return 0;

9
1. ^include <iostream>
using namespace std;
ostream Stabs(ostream &stream)
{
stream '\t' '\t' f\t';
stream.width(20);
return stream;
int main ()
cout tabs "";
return 0;

2. ^include <iostream>
^include <cctype>
using namespace std;
istream Sfindalpha(istream sstream)
char ch;
do {

stream.get(ch);
} while{Jisalpha(ch));
return stream;
}

605

C++

606

int

main{)

char str[80];
cin findalpha str;
cout str "\n";
return 0;
!

3. //
^include <iostream>
^include <fstream>
^include <cctype>
using namespace std;
int main(int argc, char *argv[])
{
char ch;
if(argc!=3) {
cout " <> <_>\";
return 1;
ifstream in{argv[l] ) ;
if(!in> {
cout " \";
return 1 ;
}
ofstream out (argv[2] ) ;
if ( l o u t ) {

cout " \";


return 1;
while ( !in. eof {)) {
ch = in . get ( ) ;
if (iin.eof () ) {
if (islower {ch) ) ch = toupper(ch);
else ch = tolower(ch);
out. put (ch) ;

in. close () ;
out. close () ;

^.
return 0;

4. //
ttinclude <iostream>
^include <fstream>
^include <cctype>
using namespace std;
int alpha [26];
int main (int argc, char *argv[])
{
char ch;
if(argc!=2) {
cout ": <_>\";
return 1;
}
ifstream in(argv[l]);
if(!in) {
cout " ";
return 1;
}
// alpha []
int i ;
for(i=0; i<26; i++) alpha [i] = 0;
while ( ! in.eof {) ) {
ch = in. get () ;
if (isalpha (ch) ) { // ,
ch = toupper (ch) ;
alpha[ch - 'A']++; // 'A' - 'A1 == 0,
// 'B' - 'A' == 1, . .

//
for (i-0; i<26; i++) {
cout (char) ('A' -(- i) ": " alpha [i] '\n'
in. close () ;
return 0;

607

608

5. //
^include <iostrearn>
^include <fstreara>
linclude <cctype>
using namespace std;
int main(int argc, char *argv[])
{
char ch;
if(argc!=3) {
cout " <> <>\";
return 1;
ifstream in {argv [1] ) ;
if ! in) {
cout " ";
return 1;
of stream out {argv [2] ) ;
if (lout) {
cout " "
return 1;
while ( lin.eof () ) (
ch = in. get ( ) ;
if ( ! in. good (} && lin.eof ()) return 1
if (lin.eof 0) {
if (islower (ch) ) ch = toupper(ch)
else ch = tolower(ch);
out .put (ch) ;
if ( lout. good ( ) ) return 1;

in.close();
out.close();
if (!in.good{) S5 lout.good()) return 1
return 0;

5.//
ttinclude <iostream>
^include <fstream>

609^

#include <cctype>
,
using namespace std;
int alpha [26];
int m a i n f i n t argc,

char * a r g v [ ] )

char ch;
if(argc!=2) {

cout ": <_>\";


return 1;
1

ifstream in(argv[l]);
cout " ";
return 1;
// alpha[]
'int i;
for(i=0; i<26; i++) alpha[i] = 0;

while(lin.eof()) {
ch = in.get();
if(!in.good() s& lin.eof ()) return 1;
if(isalpha(ch)) { // ,
ch = toupper(ch);
alpha[ch - 'A']++; // 'A1 - 'A' == 0,
// 'B' - 'A' == 1, . .

};
//
for(i=0; i<26; i--) {
cout (char) ('A' + i) ": " alpha[i] '\n';
1
in. close () ;
if(!in.good()) return 1;
return 0;

6. (get) seekg().
(put) seekp().

610

C++


1. ^include <iostream>
^include <fstream>
^include <cstring>
using namespace std;
ftdefine SIZE 40

class inventory {
char item[SIZE]; //
int onhand; // ,
double cost; //
public:
inventory(char *i, int o, double c)

{
strcpy(item, i);
onhand = o;
cost - c;

}
void store(fstream sstream);
void retrieve(fstream &stream};
friend ostream &operator (ostream ustrearn, inventory ob);
friend istream &operator (istream fistream, inventory Sob);
};
ostream &operator (ostream Sstream, inventory ob)

{
stream ob.item ": " ob.onhand;
stream " $" ob.cost '\n';
return stream;

)
istream ^operator (istream Sstream, inventory &ob)

{
.cout " : ";
stream ob.item;
cout " : ";
stream ob.onhand;
cout " : ";
stream ob.cost;
return stream;

}
void inventory::store(fstream Sstream)
{
stream.write(item, SIZE);

61

stream. write ( (char *) sonhand, sizeof (int) ) ;


stream. write ( (char *) ficost, sizeof (double) ) ;
void inventory::retrieve(fstream sstream)
stream, read(item, SIZE);
stream.read((char *) fionhand, sizeof(int));
stream.read((char *) ficost, sizeof(double));
)

int mainf)
fstream invC'inv", ios::out I ios: :binary) ;
int i;
inventory pliers("", 12, 4.95);

inventory hammers("", 5, 9.45);


inventory wrenches{"", 22, 13.90);
inventory tempC'", 0, 0.0);
if(!inv} {

cout " \";


return 1;
//
pliers.store(inv);
hammers.store(inv);
wrenches.store(inv);
inv. close {) ;
//
inv.open("inv", ios::in I ios::binary);
if(!inv) {
cout " ";
return 1;
do {

cout " # ( -1) : ";


cin i;
if(i == -1) break;
inv.seekg{i* (SIZE-t-sizeof (int) -fsizeof (double) ) , ios: :beg) ;
temp. retrieve (inv) ;
cout temp;
} while (inv. good {) ) ;

612

C++
inv.close ();
return 0;

10

1. ^include <iostream>
using namespace std;
ostream fisetsci (ostream fistream)
{
stream. set f (ios: : scientific I ios: : uppercase) ;
return stream;

)
int main ( )
{
double f = 123.23;
cout setsci f;
cout '\n';
return 0;

2. //
^include <iostreara>
^include <fstream>
using namespace std;
int mainiint argc, char *argv[]}
{
if(argc!=3) {
cout ": <> <>\";
return 1;

ifstream in(argv[l]};
if(!in) {
cout " ";

return 1;

ofstreara out (argv[2j ) ;


if ( l o u t ) {
cout " \" ;
return 1 ;
char ch.;
int i = 8;
while ( ! in. eof (} ) {
in. get (ch) ;
i f ( c h = = ' \ t ' ) f o r { ; i>0; i --) o u t . p u t C '
else out. put {ch};
if (i==-l j I ch=='\n') i = 8;
i ;
in. close ( ) ;
out .close {}
return 0;

3. //
^include <iostream>
#include <fstrearn>
^include <cstring>
using namespace std;
int mainlint argc, char *argv[]}
{
if (argc!=3) {
cout ": <> <>\
return 1 ;
ifstream in(argv[l]);
ifUin) {
cout " \";
return 1;
char str[255] ;
int count = 0;
while (! in. eof (} ) i
in str;
if ( !strcmp(str, argv[2])) count++;

613

614

C++

cout argv[2] " " count;


cout " . \";
in. close () ;
return 0;

4. :
out.seekp (234, ios: :beg) ;

5. rdstate(), good(), eof(), fail() bad().


6. / C++
.

10.2
1. ^include <iostream>
using namespace std;
class num {
public:
int i;
num(int x) {i = x; }
virtual void shownumO ( cout i '\n'; }
class outhex: public num {
public:
outhex (int n) : num{n) {}
void shownumO ( cout hex i ' \ n ' ; }

class outoct: public num {


public:
outoct(int n) : num(n) { }
void shownumO { cout oct i ' \ n ' ; }
int main()
{
outoct o(10) ;

outhex h(20};
o. shownumO ;
h . shownum ( } ;

6/5

return 0;

2. # include <iostream>
using namespace std;
class dist {
public:
double d;
dist (double f) {d - f; }
virtual void trav_time{}
1
cout " 60 /:";
cout d / 60 '\n';

class metric: public dist {


public:
metric(double f ) : dist(f) {}
void trav_time()
{
cout " 100 /:";
cout d / 100 '\n';

int main()
{
dist *p, mph(88.0) ;
metric kph(88) ;
p = &mph;
p -> trav__time ( ) ;
p = &kph;
p -> trav_time (} ;
return 0;

10.3
2. , ,
. ,
. , , .

616

C++

3. funcQ derivedl ftincO base. ,


.

10.4
1. //
#include <iostream>
# include <cstdlib>
using namespace std;
class list {
public:
list *head;
list *tail;
list *next;
int num;

//
//
//
//

list () { head = tail = next = NULL; }


virtual void store (int i) = 0;
virtual int retrieve () = 0;

//
class queue: public list {
public:
void store (int i) ;
int retrieve (} ;

void queue: : store (int i)


{
list *itern;
item = new queue;
if (! item) {
cout " \";
exit(l) ;
}
item -> num = i;
//
if (tail) tail -> next = item;
tail = item;
item -> next = NULL;
iff! head) head = tail;

int queue: : retrieve ()


{
int i;
list *p;
if (! head) {
cout " \";
return 0;

//
i = head -> num;

p = head;
head = head -> next;
delete p;
return i;

//
class stack: public list {
public:
void store (int i);
int retrieve (} ;

};
void stack: : store (int i)
I
list *item;
item = new stack;
if (! item) {
cout " \
exit ( 1 ) ;
i

item -> num = i;


//
if (head) item -> next = head;
head = item;
if ('tail) tail = head;

I
int stack : : retrieve ( )
{
int i;
list *p;
if (! head) {
cout " \";

617

618

return 0;
//
i = head -> ;
= head;
head = head -> next;
delete p;
return i;
1

//
class sorted: public list {
public:
void store (int i) ;
int retrieve () ;
};
void sorted: : store (int i)
f
list *item;
list *p, *p2;
item = new sorted;
if (! item) {
cout " \";
exit(l);
}
item -> nura = i;
//
= head;
2 = NULL;
while () { //
if (p->num > i) {
item -> next = p;
if(p2) p2 -> next = item; //
if (p==head) head = item; //
break;
1
p2 = p;
p = p -> next;
}
if{!p) { //
if (tail) tail -> next = item;
tail = item;
item -> next = NULL;

C++

i f ( ! h e a d ) //
head = item;

int sorted: :retrieve()


{
int i;
list *p;
if(lhead) {
cout " \";
return 0;

//
i = head -> num;
p = head;
head = head -> next;
delete p;
return i;

int main()
(
list *p;
//
queue q ob;
i- //
/ /
p - q_ob;
p -> store (1} ;
p -> store (2) ;
p -> store (3} ;
cout : ": ";
cout p -> retrieve ( ) ;
cout p -> retrieve C);
cout p -> retrieve ();
cout '\n';
//
stack s_ob;
p = &s_ob; //
p -> store (1) ;
p -> store (2) ;
p -> store (3) ;
cout ": ";
cout p -> retrieve (};

6/9

620

__

C++

cout -> retrieve!);


cout -> r e t r i e v e d ;
cout ' \ n ' ;

//
sorted sorted_ob;
p = &sorted_ob;
p
p
p
p
p

->
->
->
->
->

cout
cout
cout
cout
cout
cout

store (4) ;
store (1) ;
store (3) ;
store (9) ;
store (5) ;
" : " ;
p -> retrieved;
p -> retrieved;
p -> retrieved;
p -> retrieved;
p -> retrieved;

cout '\n';
return 0;

10
1. , , . (overriding).
2. , ,
.
3.
.
, ,
, .
4. ,
.
5. ,
, . ,
, , .
6. , ,

621

, . , f() .
7. .


1. //
^include <iostream>
#include <cstdlib>
using namespace std;
class list (
public:
list *head;
list *tail;
list *next;
int num;

//
//
//
//

list () ( head = tail = next = NULL; }


virtual void store(int i) = 0;
virtual int retrieved = 0;
//
class queue: public list (
public:
void store(int i) ;
int retrieve d;
queue operator+(int i) { store (i); return *this; }
int operator (int unused) { return retrieved; }
}
void queue::store(int i)
list *item;
item = new queue;
if (!item) {
cout " \";
exit(l);
item -> num = i;
//
if(tail) tail -> next = item;
tail = item;
item -> next = NULL;
if('head) head = tail;

622

int queue : : retrieve ( )


{
int i ;
list *p;
if (! head) {
cout " \";
return 0;

//
i = head -> num;
= head;
head = head -> next;
delete p;
return i;

//
class stack: public list {
public:
void store{int i) ;
int retrieve ( ) ;
stack operator^- (int i) { store(i); return *this; }
int operator {int unused) { return retrieved; }

void stack: :store (int i)


{
list *item;
item = new stack;
if (! item) {
cout " \";
exit (1) ;
}
item -> num = i;
//
if (head) item -> next = head;
head = item;
iff! tail) tail - head;

int stack: : retrieve (}


{
int i;
list *p;

C++

623

if (!head) {
cout " \";
return 0;

//
i = head -> num;
= head;
head = head -> next;
delete p;
return i;

int main()
{
//
queue q_ob;

q__ob + 1;
q_ob + 2;
q_ob + 3;
cout
cout
cout
cout

" : " ;
q_ob ;
q_ob ;
q_ob ;

cout r\n' ;
//
stack s_ob;

s_ob + 1;
s_ob + 2;
s_ob 4 3;
cout
cout
cout
cout

": ";
s_ob ;
s_ob ;
s_ob ;

cout '\n' ;
return 0;

2. ,
, .

( ,
), .

624

C++

11

1. ,
virtual
.
2. ,
. ,
..
, , , , .
3. .
4.
,
.
5. .
.

11.1
2. tinclude <iostream>
using namespace std;
template <class X> X min(X a, X b)
{
if(a<=b) return a;
else return b;
}
int main()
{
cout min(12.2, 2.0);
cout endl;
cout min(3, 4);
cout endl;
cout min('c', 'a');
return 0;

625

3. # include <iostreara>
^include <cstring>
using namespace std;
template <class X> int find(X object, X *list, int size)
{
int i;
for(i=0; i<size; i
if (object == listfi]} return i;
return -i;
int main{)
int a[]=U, 2, 3, 4};
char *=" ";
double d[]-{l.l, 2.2, 3.3};
cout find(3, a, 4);

cout endl;
cout find('a', c, (int) strlen(c));
cout endl;
cout find(0.0, d, 3);
return 0;

4. ,
, . (, .)
, C++, " ".

11.2
2. //
^include <iostream>
using namespace std;
tfdefine SIZE 100
template <class Qtype> class q_type (
Qtype queue[SIZE]; //
int head, tail;
//
public:
q_type() { head = tail =0; }
void q(Qtype num); //

626

C++
Qtype deq{};

//

};
//
template <class Qtype> void q_type<Qtype>::q(Qtype num)
{
if (tail+l==head || (tail+l==SIZE && Ihead)) {
cout " \";
return;
}
tail-H-;

if {tail==SIZE) tail = 0; //
queue[tail] = num;
}

//
template <class Qtype> Qtype q_type<Qtype>::deq ()
{
if {head == tail) {
cout " ";
return 0; // -
}

head++;
if(head==SIZE) head = 0;
return queue[head];

//

int main{)
{
q_type<int> ql;
q_type<char> q2;
int i;

for(i=l; i
ql.q(i);

for(i=l; i
cout " " ql.deqO "\n
cout " " q2.deq() "\n

}
return 0;

3. ^include <iostream>
using namespace std;

627

template <class X> class input {


X data;
public:
input (char *s, X man, X m a x ) ;

template <class X>


input <X> :: input (char *s, X min, X max)
{
do {
cout s "; ";
cin data;
} while (data<min [| data>max) ;
}
int main{)
{
input<int> 1(" ", , 10);
input<char> (" ", 'A', 'Z'};
return 0;

11.3
2. throw , try.
3. , catch
. (
catch.)
4. , catch, terminate(), .

11.4
2. throw catch.
3.
catcb(int).
catch(...).
4. catch(,..).
5. ^include <iostream>
^include <cstdlib>
using namespace std;

628
double divide (double a, double b)
{
try {
if(!b) throw (b);
}
catch (double) {
cout " \";
exitU);
}
return a/b;
int mainO
cout divide(10.0, 2.5) endl;
cout divide(10.0, 0.0);
return 0;

11.5
1. new . new(nothrow) .
2. = new(nothrow) (int);
if(!p) (
cout " \";

try {
= new int;
} catch (bad alloc ba} {

cout " \";

1 1
1. ^include <iostream>
^include <cstring>
using namespace std;
//
//
template <class X> X mode(X *data, int size)

.
register int t, w;
X md, oldmd;
int count, oldcount;
oldmd = 0;
oldcount = 0;
for(t=0; t<size; t++) {
md=data [ t ] ;
count = 1;
for(w = t+1; w < size; w+-l-)
if (md==data [w] ) count++
if {count > oldcount) {
oldmd = md;
oldcount = count;

return oldmd;
int main ()
{
int i[] = {1, 2, 3, 4, 2, 3, 2, 2, 1, 5};

char *p = " ";


cout " : " rnode(i, 10) endl
cout " : " mode (p, (int)
strlen (p) ) ;
return 0;

2. ^include <iostream>
using namespace std;
template <class X> X sum(X *data, int size)
I
int i;
X result = 0;

for{i=0; i<size; i++) result += data[i];


return result;
1

int main ( )
int i[] - {1, 2, 3, 4};
double d[] = {1.1, 2.2, 3.3, 4.4};

629

630

cout surn{i, 4) endl;


cout sum(d, 4) endl;
return 0;

3. ^include <iostream>
using namespace std;
//
template <class X> void bubble (X *data, int size)
{
register int a, b;
X t;

for{a=l; a<size;
for (b=size-l; b>=a; b )
if(data[b-l] > data[b])
t = data[b-l] ;
data[b-l] = data[b]
data[b] = t;

int main{)
int i[] = {3, 2, 5, 6, 1, 8, 9, 3, 6, 9);
double d[] = {1.2, 5.5, 2.2, 3.3};
int j ;

bubble{i, 10);
bubble (d, 4);

// int
// double

for(j=0; j<10; j++) cout i[j]


cout endl;
for(j=0; j<4; j++) cout d[j] '
cout endl;
return 0;

4. //
^include <iostream>
using namespace std;
ttdefine SIZE 10
//
template <class StackType> class stack {

C++

StackType stckfSIZE] [2] ; //


int tos;
//
public :
void init() { tos =0;}
void push (StackType ob, StackType ob2) ;
StackType pop (StackType &ob2);
I;
//
template <class StackType>
void stack<StackType>: : push (StackType ob, StackType ob2)
I
if (tos==SIZE) (
cout " \";
return;

>
stck[tos] [0] = ob;
stck[tos] [1] = ob2;
tos++;

//
template <class StackType>
StackType stack<StackType>: : pop (StackType &ob2)

if (tos 0) (
I

cout " \";


return 0; //

tos ;
ob2 = stck[tos] [1];
return stck[tosj [0] ;

}
int main ()
{
//
stack<char> si, s2; //
int i ;
char ch;
//
sl.initO ;
s2.init() ;

s 1 . push ( ' a ' , ' b ' ) ;


r r r
s2.push('x , z ) ;
sl.pusht'b', 'd') ;

63?

632

____

s2.push( ' ' , ' ' ) ;


s l . p u s h { ' c ' , 'a' ) ;
s2.push('z', ' x ' ) ;

for(i=0; i<3; i++) f


cout " 1:" sl.pop(ch);
cout ' ' ch "\n";

}
for{i=0; i<3; i-n-J {

cout " 2:" s2.pop(ch);


cout ' ' ch "\n";
}

// double
stack<double> dsl, ds2; //
double d;
//
dsl.init () ;
ds2.init() ;
dsl.pushfl.l,
ds2.push{2.2,
dsl.push(3.3,
ds2.push(4.4,
dsl. push (5. 5,
ds2.push(6.6,

2.0);
3.0);
4.0);
5.0);
6.0) ;
7.0);

for(i=0; i<3
cout " 1:" dsl. pop (d);
cout ' ' d "\n";
for(i=0;
cout " 2:" ds2.pop(d);
cout ' ' d "\n";
return 0;

5. try, catch throw:

try {
// try
throw _
catch (type arg) {
// .

C++

633

6. /* stack,

*/
ttinclude <iostream>
using namespace std;

^define SIZE 10
// stack
template <class StackType> class stack (
StackType stck[SIZE]; //
int tos;
//
public:
void init() { tos = 0;} //
void push (StackType ch) ; //
StackType pop ; //

//
template <class StackType>
void stack<StackType>: :push(StackType ob)
{
try {
if (tos=SIZE) throw SIZE;
}
catch (int) {
cout " \";
return;

}
stck[tos] = ob;
tos++;
//
template <class StackType>
StackType stack<StackType>: :pop()
{
try {
if (tos==0) throw 0;
i
catch (int) {
cout " \";
return 0; //

)
tos ;
return stckftos];

634

++
int

main()

{
//
stack<char> si, s2; //
int i;
//
sl.initO ;

s2.init()j
si.push('a')
s2.push('x'J
sl.pushCb1 )
s2.push('y')
si.push('c1)
s2.push{'z')
for(i=0; i<3
for{i=0; i<4

i++) cout " 1:" sl.popO "\n";


cout " 2:" s2.pop(J "\n";

// double
stack<double> dsl, ds2; //
//
dsl.initO ;
ds2.init () ;
dsl.push(1.1);
ds2.push(2.2);
dsl.push(3.3);
ds2.push(4.4);
dsl.push(5.5};
ds2.push(6.6);
for(i=0; i<3; i++) cout " 1:" dsl.pop(J "\n
for(i=0; i<4; i++) cout " 2:" ds2.pop() "\n
return 0;

8. new , ,
( ).
, new ,
,
,
.

'

'

635

12

1. C++ . template.
:
template <class

Ttype> _ _(_)

2. C++ ,
.
:
template <class Ttype> class _

3. ^include <iostream>
using namespace std;
// b
template <class X> X gexp{X a, X b)
{
X i, result = 1;
for(i=0; i<b; i++) result *= a;
return result;

}
int main()
{
cout gexp(2, 3) endl;
cout g e x p U O . O , 2 . 0 ) ;
return 0;

4. ttinclude <iostreara>
ttinclude <fstream>
using namespace std;

C++

636

template <class CoordType> class coord (


CoordType x, y;
public:
coord(CoordType i, CoordType j ) { x = i; = j; }
void show() { cout x ", " endl; }
int main()
{
coord<int> old, 2), o2{3, 4);
ol.show() ;
o2.show(};
coord<double> o3{0.0, 0.23), o4(10.19, 3.098);
o3.show();
o4.show();
return 0;

5. try, catch throw . , , try. throw catch.

6. .
7. terminate() ,
throw, catch. unexpected()
, throw.
8. catch(...)

12.1
1. , C++ , .
2. BaseClass ,
:

637

i int
BaseClass
BaseClass
BaseClass

3. .
4. if(typeid{*p) == typeid(D2)) ...
5. . , , .

12.2
1. dynamic_cast .
2. ^include <iostreara>
#include <typeinfo>
using namespace std;
class {

virtual void f() {}


};

class Dl: public (


void f() {}
>;
class D2: public {
void f(J {}

};
int main { )
(
*;
D2 Ob;

p = dynamic_cast<D2 *> (sob);


if{p) cout " ";
else cout " ";
return 0;

3. int main
{
int i ; ;
Shape *p;

638

+->-

for(i=0; i
p = generator!); //
cout typeid(*p) .name ( ) endl;
// ,
// NullShape
if {!dynamic_cast<Null3hape *> (p) )
p->example () ;
j

return 0;

4. . Dp ,

12.3
1, .
2. ^include <iostream>
using namespace std;
void f (const double Si)
{
double sv = const_cast<double s> (i) ;
v = 100.0;
}

int main()
{
double x - 98.6;

cout x endl;
fix);

cout x endl;
return 0;

3. const_cast const,
.

639

12
1. typeid type_Jnfo,
,
2. typeid <typeinfo>.
3. .

dynamic_cast

reinterpret_cast

static_cast

""

const_cast

const

4. #include <iostream>
# include <typeinfo>
using namespace std;
class A {
virtual void f{)

{}

1;
class B: public A {

1;
class C: public {
int main ( )

{
A *p, a__ob;
b_ob;
c_ob;
int i;
cout " , "
cout "1 ";
cout "2 .\";

cin i;
if (i==l) p = fib_ob;
else if(i==2) p = ic_ob;
else p = &a_ob;

C++

640

if(typeid(*p) == typeid(A)
cout " ";
if (typeidt*p) == typeid(B}
cout " ";
if(typeid(*p) == typeid(C)
cout " ";
return 0;

5. typeid dynamic_cast ,
typeid .
6. typeid type_info.


1. genera tor(),

.
/*

V
Shape *generator()

try {
switch{rand{) % 4)
case 0:
return new
case 1:
return new
case 2:
return new
case 3:
return new

{
Line;
Rectangle;
Triangle;
NullShape;

catch (bad_alloc ba) {


return NULL;
}
return NULL;

2. generator(), new(nothrow).

641

// new(nothrow)
Shape *generator()
I
Shape *temp;
s w i t c h ( r a n d ( ) % 4) {
case 0:

return
case 1:
return
case 2:
return
case 3:
return

new(nothrow) Line;
new(nothrow) Rectangle;
new(nothrow) Triangle;
new(nothrow) NullShape;

if(temp) return temp;


else return NULL;
J

13

1. , C++ , :

dynamic_cast
reinterpret_cast

static_cast

""

const_cast

const

2. type_info ,
. typejmfo
typeid.
3. typeid.
4. if(typeid(Derived) == typeid(p*))
cout " Derived\n";
else
cout " Base\n";

642

C++

5. "".

6. .

13-1
1. /* |
"using namespace std"
*/
^include <iostream>
linclude <fstream>
int main(int argc, char *argv[])

if(argc!=3) {
std::cout " <_> <_>";
return 1;
1

std::ifstream fin(argv[l]); //
std::ofstream fout(argv[2]); //
if(!fout) {
std::cout " ";
return 1;
if(!fin) {
std::cout " ";
return 1;
char ch;
fin.unsetf{std::ios::skipws); //
while{!fin.eof(}) {
fin ch;

if (ch1 '} ch = ' | ';


1

if(Ifin.eof()) fout ch;

fin.close();
fout.close();
return 0;

643

2. , .
3. using :
using _;:;

using :
using namespace _;
4. C++, cin cout, std,
std.
C++ ,
, .

std::.
using , . . using std::cin using
std::cout.
5. ,
.

13.2
1. //
^include <iostreara>
#include <cstring>
using namespace std;
class strtype {
char str[80];
int len;
public:
strtype(char *s) { strcpy(str, s); len = strlen(s); }
operator char *() { return str; }
operator int() { return len; }

int main ()
strtype s(" ");
char *p;
int 1;
1 = s; // s
= s; // s

644

__

C++

// char *
cout ": \";
cout "\ " 1 " . \" ;
return 0;

J
2. ^include <iostream>
using namespace std;
int p(int base, int exp) ;
class pwr (
int base;
int exp;
public:
pwr (int b, int e) { base = b; exp = e; }
operator int() f return p(base, exp}; }
// base exp
int p(int base, int exp)

' int temp;


for(temp=l; exp; exp ) temp = temp * base;
return temp;
int main()

pwr ol(2, 3), o2(3, 3);


int result;
result = ol;
cout result '\n';
result = o2;
cout result '\n';
// cout,
//
cout ol + 100 '\n';
return 0;

13.3
1. //
#include <iostream>

_R

645

^include <cstring>
using namespace std;
class output {
static char outbuf [255] ; //
static int inuse; // inuse ,
// ;
static int oindex; //
char str[80] ;
int i; // str
int who; // ,
public :
output{int w, char *s) ( strcpy(str, s) ; i = 0; who = w; }
/* -1 ,
0 , who,

*/
int putbuf ( )
{
if(!str[i]) { //
inuse =0; //
return 0; //
}
if (! inuse) inuse = who; //
if(inuse != who) (
cout "" who " \";
return -1; // -
}
if (str [i]) { //
outbuf [oindex] = str[i];
cout " " who " \";
i++; oindex++;
outbuf [oindex] = r\0'; //
return 1;
}
return 0;
}
void show() ( cout outbuf '\n'; }
char output :: outbuf [255] ; //
int output :: inuse = 0; // inuse ,
// ;
int output: : oindex =0; //
int main ()
{
output ol(l, " "), 2(2, " ");

C++

while(ol.putbuf() I o 2 . p u t b u f ( ) ) ; //
..show();
return 0;
I

2. ^include <iostream>
# include <new>
using namespace std;
class test {
static int count;
public:
testC) { count-t-+; }
~test() { count ; }
int getcountO { return count; }

int test::count = 0;
int main()
test ol, o2, o3;
cout ol.getcount() " ";
test *p;
/*

*/
try {
= new test; //
if(!p) { //
cout " ";
return 1;

} catch(bad_alloc ba) { //
cout " \";
return 1;

cout ol.getcount () ;
cout " \
//
delete ;
cout ol.getcount {};

647

cout " ";


return 0;

13.4
1. current
, countingO :
//
ttinclude <iostream>
using namespace std;
class CountDown {
int incr;
int target;
mutable int current; // current
public:
CountDown (int delay, int i = 1) (
target = delay;
incr = i;
current = 0;
i

bool counting ( ) const {


current +- incr;
if {current >= target) {
cout "\a";
return false;
}
cout current " ";
return true;

int mainO
{

CountDown ob(100, 2 ) ;
while (ob. counting ( ) ) ;
return 0;
1

2. , . - -, - .

648

_+_+_

13.5
1- 2. , C++ int
double.
3. , . ,
, . , , ,
.

13.7
1. /* ,

*/
^include <iostream>
^include <strstream>
using namespace std;

int main{)
{
char buf[255];
ostrstream ostr(buf, sizeof buf);
ostr "/ ";
ostr " , /\ " 103;
ostr ' ' 123.23 '\';
//
ostr hex 100 ' ';
//
ostr.setf(ios::scientific);

ostr dec 123.23;


ostr endl ends; // ,
//
//
cout buf;
cout ostr.pcount();
return 0;

2. /* /

*/
^include <iostream>
#include <strstream>
using namespace std;
char inbuf[] = " / C++,
";
char outbuf [255] ;
int main ()
{
istrstream istr(inbuf);
ostrstream ostr (outbuf , sizeof outbuf};
char ch;
while ( ! istr.eof () ) {
istr.get (ch) ;
if (listr.eof ()) ostr. put {ch) ;
}
ostr. put (' \0' ); //

cout ": " inbuf '\n';


cout ": " outbuf '\n';
return 0;

3. //
#include <iostream>
#include <strstream>
using namespace std;
int main()
{
float f;
char s [ ] = "1234.564"; //
istrstream istr(s);
//
//
istr f;
cout " : " f '\n';
return 0;

649

650

C++

13
1. -, ,
, -
,
.
2. /
<strstream>.

3. .
4. extern "" int counter ;

5. ,
. ,
C++.
6. explicit . .
7. - ,
.
8. , namespace,
.
9. mutable
, .


1. . , ,
, .

2. .
3. ,
.

, .

14

1. C++ . -

657


.
2. - , const. :
int f ( i n t a) con3t;

3. . mutable () - - .
4. class X {
int a, b;
public:
X ( i n t i, int j) { a = i, b = j ; }
operator i n t ( ) { return a+b; }

5. , .
6. . explicit
int Demo.

14.1
1. , .
, . .
2. .
3. : , , , .

14.3
2. , , .
3. // Coord
#include <iostream>
^include <vector>
using namespace std;

C++

652

class Coord {
public:
int x, y;
Coord(} { x = = 0; }
Coord(int a, int b) ( x = ; = b; }

boll operator<(Coord a, Coord b)


return (a.x + a.y) < (b.x + b.y);

boll operator==(Coord a, Coord b)


return (a.x + a.y) == (b.x + b.y);

int main ()
vector<Coord> v;
int i;
for(i=0; i
v.push_back(Coord(i, i)) ;
for (1=0; i < v . s i z e ( ) ; i
cout v [ i ] . x "," v [ i ] . y " ";
cout endl;
for(1=0; i < v . s i z e d ; i++)
v [ i ] . x = v [ i ] . x * 2;
for(i=0; K v . s i z e l ) ; i++)
cout v [ i ] . x "," v [ i ] . y " ";
return 0;

14.4
2. //
^include <iostream>
tinclude <list>
using namespace std;
int mainO

-
list<char> 1st; //
int i;

for{i=0; i<10; i++) lst.push_back( 'A' + i) ;


cout " = " 1st. size () endl;
list<char>: : iterator p;
cout ": ";
for(i=0; i<lst.size{) ; i++) {
p = 1st. begin (} ;
cout *p;
1st .pop_front (} ;
lst.push_back(*p) ; //
}
cout endl;
if (list. empty () )
cout " \" ;
return 0;
}

:
= 1 0
: ABCDE FGHI J


. .
sizeQ .
3. //
ttinclude <iostream>
#include <list>
^include <cstring>
using namespace std;
class Project {
public:
char name [40] ;
int days_to_completion;
Project (} {
strcpy(name, " ");
days_to_completion = 0;

C++

554
Project (char *n, int d) {
strcpy (name, n) ;
days_to_completion = d;
void add_days(int i) {
days_to_completion += i

void sub_days ( int i) (


days_to_completion -= i;
}
bool completed () { return !days_to_corapletion; }
void report () {
cout name ": ";
cout days_to_completion;
cout " \";

bool operator< (const Project &a, const Project &b)


{
return a.days_to_completion < b. days_to__completion;
}
bool operator> (const Project sa, const Project &b)
{
return a.days_to_completion > b.days__to_completion;
}
bool operator== (const Project &a, const Project &b)
(
return a.days_to_completion == b.days_to_completion;
}
bool operator != (const Project &a, const Project sb)
{
return a.days_to_completion != b. days_to_completion;
}
int main()
(
list<Project> proj;
list<Project> proj2;
proj -push_back (Project (" ", 35) ) ;
proj .push_back (Project (" ", 190));
proj. push back(Project (" STL", 1000));

.
proj2.push_back(Project(" ", 780));
proj2.push_back(Project{" ", 50));
proj2.push_back(Project(" COM", 300));
proj.sort();
proj2.sort(} ;
proj.merge(proj2); //
list<Project>::iterator p = proj.begin();
//
while(p != proj.end()) {
p->report(};
p-H-;
J

return 0;

14.5
2. //
^include <iostream>
^include <niap>
^include <cstring>
using namespace std;
class name (
char str[20] ;
public:
nameU { strcpyfstr, "") ; }
name (char *s) { strcpy(str, s) ; }
char *get() { return str; }
// name < ()
bool operator< (name a, name b)

<

return strcmp (a. get {) , b.getO) < 0;

class phonenura {
char str[20] ;
public:
phonenumO { strcmp(str, ""); }
phonenum(char *s) { strcpyfstr, s) ; }
char *get() { return str; }

655

656

++_

int main{}

{
map<name, phonenum> m;
//
//
m.insert(pair<name, phonenum>
(name ("") , phonenuin("541-85-51") ) ) ;
m.insert(pair<name, phonenum>
(name(""), phonenum("550-09-96")));
m.insert(pair<name, phonenum>
(name (""), phonenum("8-3712-41-16-36")));
ra.insert (pair<name, phonenum>
{("") , phonenum("8-095-967-85-85") ) ) ;
//
char str[80];
cout " ; ";

cin str;
map<name, phonenum>::iterator p;
p = in. find (name (str) ) ;
if (p i= m.end() )
cout " : " p->second.get();
else
cout " \";
return 0;

3. .

14.6
1. // sort
^include <iostream>
^include <vector>
tinclude <cstdlib>
^include <algoritm>
using namespace std;
int main ()
{
vector<char> v;

int i;
//

for(i=0;
v.push_back('A' + (rand()%26) ) ;
cout " : ";
for (i=0; i<v. size () ; i++)
cout v[i] " ";
cout endl endl;
/ /
sort ( v . begin ( ) , v . end ( } ) ;
cout " : ";
for(i=0; i<v.size(); i++)
cout v[i] " ";
return 0;

2. // merge
^include <iostream>
^include <list>
^include <algoritm>
using namespace std;
int main ( )

<
list<char> Istl, Ist2, Ist3(20);
int i ;

for(i=0; i<10; i+=2) Istl .push_back ( 'A' -t- i) ;


for(i=0; i<ll; i+=2} Ist2 .push_back ( 'A' + i) ;
cout " Istl: ";
list<char>: : iterator p = lstl.begin.0 ;
while (p != Istl. end () ) {
cout *p;
P++;
}
cout endl endl;
cout " Ist2: ";
p = Ist2. begin (} ;
while(p != Ist2.end() ) {

cout *p;
P++;

}
cout endl endl;

657

658

__

//
merge (Istl. begin ( ) , Istl.endO ,
Ist2.begin(), Ist2.end(),
Ist3. begin (} ) ;
cout " : ";
= Ist3.begin( ) ;
while(p != Ist3.end() ) {
cout *p;

return 0;

14.7
1. ^include <iostream>
#include <string>
ttinclude <list>
using namespace std;
int
{

itiain()
list<string> str;
str.push_back(string(""});
str.push_back(string(""));
str.push_back{string(""));
str.push_back(string(""));
str.push_back(string(""));
str.push__back(string ("") ) ;
str.push_back(string(""));
str.push_back(string(""));
str.push_back(string(""));
str.push_back(string(""));
str.sort(); //
list<string>::iterator p = str.beginf)
while (p != str.endO) {
cout *p " ";
P++;
}
return 0;

++

659

2. ^include <iostream>
^include <string>
^include <algorithm>
using namespace std;
int main()
{
string str;

cout " : ";


cin str;
int i = count {str. begin () , str.endf), 'e');
cout i " \";
return 0;

3. ^include <iostream>
^include <string>
^include <algorithm>
^include <cctype>
using namespace std;
int main()
string str;
cout " : ";
cin str;

int i = count_if {str.beginO , str.endO, islower) ;


cout i " \";
return 0;

4. string - basic_string.

14
1. , . , ,
-,
.

C++

660

2. , .
, . .
.
_
3. ^include <iostream>
^include <vector>
^include <list>
using namespace std;
int main {}
{
vector<int>
list<int> 1st;
int i;
for(i=0;
for(i=0;

if(!(v[i]%2)) lst.push_back(v[i])
list<int>::iterator p = 1st.begin ();
while{p != lst.end()) {
cout *p " ";
P++;
return 0;

4.
. ,
, .
5. , .


. . .1
, . .2 .
, ( )
,
.
. 1. (A-Z)

Abstract Class
Access Specifier

Algorithm

Allocator

Ambiguity

American National Standards


Institute

ANSI

Anonymous Union

Array-Based I/O

Associative Container

Automatic Bounds Checking

Base Class

Bidirectional Iterator

Bilter

Bitmask

Bounded Array

string

C++ Standard Library

C++

C++

662

. 1 ()

Casting Operator

Class

Comparison Function

Const Class Member

Constructor

Container

Container Class

Conversion Function

Copy Constructor

Default Argument

Derived Class

Destructor

Early Binding

Encapsulation

Enumeration

Exception

Exception Catching

Exception Handling

Exception Throwing

Extraction Operator

Extractor

Format Flag

Forward Declaration

Forward Iterator

Forlter

Forward Reference

Friend Function

Function Object

Function Overloading

Generated Function

663
, 1 ()

Generic Class

Generic Function

Get Pointer

Header

Header File

Heap

Hierarchical Classification

I/O Manipulator

Independent Reference

Indirect Base Class

Inheritance

In-Line Function

Input Iterator

Inlter

Input/Output

I/O

Inserter

Inserter Function

Inserter Operator

Insertion

Insertion Operation

Instantiating

International Standards
Organization

ISO

Iterator

Join

Key

Large Character Set

Late Binding

Linkage Specifier

List

Mangling

Manipulator

Map

Member

664

C++
. 1 ()

Member Function -

Merge

Microsoft Foundation Classes

MFC

MFC

Multiple Inheritance

Mutable Class Member

Name Collision

Name Mangling

Namespace

Object

Object Factory

Object Oriented Programming

OOP

Operation

Operator

Operator Function

Operator Overloading

Output Iterator

Outlter

Overloading

Overriding

Pass by Reference

Pass by Value

Permutation

Pointer

Polymorphic Class

Polymorphism

Predicate

Private

Protected

Public

Pure Virtual Function

Put Pointer

Queue

665

. 1 ()

Random Access
Random Access Iterator

Randlter

Redefinition

Reference

Reverse Iterator

Run-Time Error

Run-Time Polymorphism

Run-Time Type Identification

RTTI

Safe Array

Scope

Scope Resolution Operator

Sequence

Stack

Standard Template Library

STL

Statement

Static Class Member

Stream

String Class

String Data Type

Structure

Structured Programming
Language

Template

Template Class

Template Function

Type Promotion

Union

Unnamed Namespace

Vector

Virtual Base Class

Virtual Function

666

C++
.2. (-)

Abstract Class

Automatic Bounds Checking

Algorithm

American National Standards


Institute

ANSI

Anonymous Union

Default Argument

Associative Container

Map

Base Class

Safe Array

Unnamed Namespace

Microsoft Foundation
Classes

MFC

MFC

Standard Template Library

STL

Bitmask
Input/Output


I/O

Array- Based I/O

Vector

Virtual Function

Virtual Base Class

Exception Throwing

Insertion

In-Line Function
Bidirectional Iterator


Bilter

Destructor
Run-Time Type Identification

RTTI

Run-Time Error

Run-Time Polymorphism

Friend Function

Header

Header File

667

. 2 ()

Private

Protected

Bounded Array

Hierarchical Classification

Encapsulation

Statement

Mangling

Name Mangling

Exception

Iterator

Input Iterator

Inlter

Output Iterator

Outlter

Random Access Iterator

Randlter

Class

Container Class

Template Class

Key

Constructor

Copy Constructor

Container

Name Collision

Indirect Base Class

Manipulator

I/O Manipulator

International Standards
Organization

ISO

Multiple Inheritance

Mutable Class Member

Inheritance

Independent Reference

Ambiguity

Scope

C++

668

. 2 ()

Exception Handling

Reverse Iterator

Union

Object

Object Oriented
Programming

OOP

Function Object
Forward Iterator

Forlter

Operator

Inserter Operator

Extraction Operator

Casting Operator

Scope Resolution Operator

Operator Function

Operation

Insertion Operation

Public

Queue

Overloading

Operator Overloading

Function Overloading

Pass by Value

Pass by Reference

Redefinition

Permutation

Exception Catching

Enumeration

Heap

Overriding

Late Binding

669
. 2 ()

Polymorphism

Polymorphic Class

Generated Function

Sequence

Const Class Member

Stream

Forward Declaration

Predicate

Type Promotion

Derived Class

Random Access

Namespace

Early Binding

Allocator

Large Character Set

Generic Function

Generic Class

Merge

Join

Instantiating

Access Specifier

Linkage Specifier

List

Reference

Forward Reference

C++ Standard Library

C++

Static Class Member

Stack

string

String Class

String Data Type

Structure

C++

670

. 2 ()

Pointer

Put Pointer

Get Pointer

Object Factory

Format Flag

Inserter

Inserter Function

Extractor

Conversion Function

Comparison Function

Member Function

Template Function

Pure Virtual Function

Member

Template

Structured Programming
Language

,
"" ( Example) "" ( Exercise).
N
ChapN. , ( " "), Review. , ( " "),
Mastery. , ( " "), Cumulative.
MS-DOS ( DOS). MS Windows,

( Windows).
C++.
,.
, , .

. !

abstract class, 314


access specifier, 207
algorithm, 421
allocator, 423
ambiguity, 165
American National Standards Institute
(ANSI), 14
anonymous union, 66
array-based I/O, 411
associative container, 421

base class, 57; 207


bitmask, 244
bounded array, 137

string, 462
casting operator, 357
class, 26
comparison function, 423
const class member, 383
constructor function, 44
container, 421
conversion function, 383; 393
copy constructor, 52; 92; 149

D
default argument, 158
derived class, 57; 207
destructor, 45

E
early binding, 318
encapsulation, 11
exception handling, 325; 337

exception throwing, 337


extraction operator, 265
extractor, 265

format flag, 244


forward declaration, 101
forward reference, 101
friend functions, 97
function object, 423
function overloading, 12; 36

G
generated function, 328
generic class, 243; 325
generic function, 325
get pointer, 292

header, 15
hierarchical classification, 13

i
I/O manipulators, 254
incapsulation, 59
independent reference, 139
indirect, 223
inheritance, 13; 57
in-line, 72
Input/Output (I/O), 19
inserter, 259
inserter function, 259
insertion, 259
insertion operator, 259
instantiating, 328
International Standards Organization
(ISO), 14
iterator, 421

C++

674

key, 421

L
late binding, 318
linkage specifier, 408
list, 419

Q
queue, 419

R
random access, 292
reference, 127
reverse iterator, 422
Run-Time Type Identification (RTTI),
357

M
mangling, 409
map, 421
member, 26
member function, 27

N
namespace, 16; 18; 383

object, 12
Object Oriented Programming (OOP), 5;
9
operator overloading, 13
operator function, 176
overriding, 308

pointer, 63
polymorphic class, 307
polymorphism, 12
predicate, 423
private, 12
public, 12
pure virtual function, 314
put pointer, 292

safe array, 138


scope resolution operator, 27
sequence, 421
stack, 419
Standard C++, 10; 14; 351
Standard Template Library (STL), 332;
419
static class member, 383
stream, 242
string class, 420; 462
structured programming language, 11

template class, 242


template function, 328
template, 325
type promotion, 165

unnamed namespace, 386

V
vector, 419
virtual base class, 230
virtual function, 303; 306

675

, 314
, 421; 453

(ANSI), 14
, 66
, 158
, 446
, 421; 446

, 57
, 386;
391
,
332; 419
, 244

/
, 259
, 283
, 295
, 254
, 19
, 19
, 242
, 292
, 19; 242
, 411
C++, 19; 242
, 276
, 244
, 19
, 419; 425
, 303; 306
. , 229

, 337
, 72

, 12
, 12
, 65

, 435
, 45; 216

(RTTI), 357; 358
, 425
, 303

, 292
, 97

, 15
, 15

, 13; 205
, 11; 59
, 409

new, 351
, 337
, 337
, 421
, 422

, 26; 65
, 314
, 57; 207
, 229; 230
, 223
, 45; 216
, 13; 205
, 44; 216
, 421
, 421
, 27
, 307
, 57; 207
, 325; 332
, 420; 462
-, 44
-, 27
, 26
, 212
, 401

C++

676

, 26; 65
, 26
, 383; 401
, 383; 396
-, 424
-, 242
, 421
, 41

, 24
C++, 24
, 25
, 24
, 44; 216; 404
, 52; 92; 149
, 51
, 144
, 421
, 421; 446
, 421; 446
, 419; 425
, 421
, 419
, 419; 435
, 419
/, 295

/, 254
, 272

, 138
, 425
, 137
, 108

(ISO), 14
, 25
, 223
, 401

, 13; 57; 205


, 223
, 139
, 165

,
325; 337
, 422
, 66
, 12
, 87

, 93
, 108
, 132
, 82
, 113
-
(OOP), 5; 9; 10; 11
-, 423
, 27
, 24

delete, 118; 122


new, 118; 121
/, 19
, 259
, 265
, 197
, 13; 15
, 357
, 194
, 27;
103
, 63; 113
, 63; 113
-, 176
, 191
, 419

, 51

, 144
, 13; 175
, 12; 36
, 158
, 165

, 306
,
337

, 308
, 318
, 12
, 303; 317
, 307
, 272
, 328
, 421
, 383; 401

, 244
/, 242
, 101
, 423
, 383; 393
, 165
, 82

-, 5; 9; 10;
11

, 11
, 57
, 16; 18; 383
, 386; 391

, 318
, 423
, 325; 326
, 243; 325; 332

, 318
, 318
, 59; 207
, 408
, 419; 435
, 435
, 127

, 135
, 101
, 139
, 132
, 383

677

, 419

, 462
, 420; 462
, 65

, 65
, 165

, 63
this, 117
, 292
, 63; 113
, 304
, 292

, 15
, 244
, 244

/, 19
, 303; 306
, 306
, 308
, 259
, 72
, 45
, 97
, 265
, 44
, 12; 36
, 266
, 259
, 328
, 328
, 383; 393
, 325; 326
, 423
, 314
-, 27
-, 328

C++

678

, 314
, 26
, 212
, 401
, 383; 401
, 383; 396

, 325

, 11

WINDOWS

1. C++
1.1. - ?

1.2. C++

C++

1.3. C++
1.4. C++
1.5. .
1.6. C++
1.7.
1.8. C++
2.
2.1.
2.2.

2.3.
2.4.
2.5.
2.6.
2.7.

3.

3.1.
3.2.
3.3.
3.4. :

5
6

6
7
7

9
10
11
12
13

14

16
18
18

19
24
26
32
36
41
43
44
51

57
63
65
72
75

81

82
87
93
97

4. ,

107

4.1.
4.2. ...

108
113

680

C++

4.3. THIS

114

4.6.

127

4.4. NEW DELETE


4.5. NEW DELETE

118
121

4.7.

132

4.8.

4.9.

135

139

5.

5.1.
5.2.
5.3. OVERLOAD
5.4.
5.5.
5.6.
6.

6.1.
6.2.
6.3.
6.4.
6.5.
6.6.
6.7.



..

-

[]

7.

7.1.
7.2.
7.3.
7.4.

7.5.
8. / C++

143

144
149
157
158
165
168
175

176
178
185
186
189
194
197
205

207
212
216
223
229
239

8.1. / C++.... 242


8.2. /
244
8.3. WIDTH(), PRECISIONQ FILLQ
251
8.4. /

8.5.
8.6.
9.
/ C++
9.1.

9.2. /

254

259
265
271
272

275

681

9.3. /
9.4.
/

282

9.6. /
9.7. /

295
298

9.5.

10.

288

292

303

10.1.

304

10.2.

306

10.3.
10.4.
11.

313
317
325

11.1.
326
.2.
332
11.3.
337
11.4.

344
11.5. ,
NEW
'.
351
12.

357

12.1.

358

12.2. DYNAMIC_CAST

368

12.3. CONST_CAST, REINTERPRET_CAST STATIC_CAST


13.

376

383

13.1.
13.2.
13.3.
13.4.
13.5.
13.6. ASM

384
393
396
401
404
408

13.7. /

411

14.

14.1.
14.2. -

419

421
424

14.3.

425

14.4.

435

14.5.
14.6.

14.7. ...

446

453

462

682

^ C++

.
C++

473

475

475

1
2

2

3

3

4

475
481
483
483
485
497
499
501
501
501
507
509
513
513
515
525
527

5

6

6

7

7

8

8

9

528

528
531
538
541
542

542
543
555
563
564

564
570
573
575
576

576
578
586
589
592
592
...594

9

10

10

11

11
12

12

13

13

14

14

683

605
610
612
612
614
620
621
624
624
624
628
635
635
636
639
640
641
641
642
650
650
650
650
651
659

661

D.

671

673

"-"
:
" "
. . MS Windows XP: Home Edition Professional
. . Windows 2000 Professional.
. . Microsoft Windows 2000 Server.
. . Windows 2000
. . Microsoft Windows 2000 Server Professional.

P. Macromedia ColdFusion
. HTML 3.2 { -)
. Java ( -)
. -
" ": "MS Office XP ", "MS Access 2002",
"MS Word 2002", "MS Excel 2002"
. Microsoft Word 2002
., A. Delphi 6
. MS Excel 2002
. .
., . PC,
4-
. MS SQL Server 2000
. . HTML 4.0
., . Microsoft Access 2000
., . Microsoft Access 2002
., A. Microsoft Office 2000
., A. Microsoft Office XP
., . Java 2
. Web-
P. Word 97
.,. XML
. Adobe Illustrator 9.0
. Adobe Photoshop 6.0
. CorelDRAW 9
. Macromedia FreeHand 9
. WAP:
. PC ( )
P. Python ( -}
. ., A. A. Adobe PageMaker 7.0
. ., A. A. Adobe InDesign
. ., A. A. CorelDRAW 9:
. ., A. A. CorelDRAW 10:
. Microsoft SQL Server 7.0

848
700
960
576
1056

.
.
.
.
.

672
1040
1104
32

.
.
.
,

992 c.
1152.
1072
1008 .
1024 .
1280 .
672 .
1088 .
1040 .
728 .
928 .
1072 .
1024 .
1120.
736.
608 .
832 .
576 .
432 .
432 .
1248 .
768 .
784 .
704 .
1136 .
1136.
720 .

. . Active Server Pages ( -}


. Microsoft Outlook 2002
. CorelDRAW ( -)

672 ,
656 .
704 .

""
CD-ROM " MS Windows NT Server 4.0"
" Windows NT Server 4"
Microsoft Press. .
2- ( -)
Microsoft Press. Visual Basic 6.0
Microsoft Press. MS Windows NT Server 4.0
. Dynamic HTML ( -)
.
. Linux
. -: , ,

. Windows
. Windows 98 ( )
. .
. XSLT
. Internet 2000
. Novell GroupWise 5.5:

A. Microsoft Excel 2000:
A. Excel, VBA, Internet
., . Web- Java JavaScript
. Windows ( )
., . Delphi
. . Delphi 5 ( )
. JavaScript Web-
. . MS Excel
.
Excel 97/2000 { )
. -
. Shareware:

. .
. Borland C++ 5
. Web-
. DirectX. Delphi ( -)
. Open GL Delphi ( )
.
Java
. 3ds max 4:
. MS Office Project
. . Motorola
. . , ,
.

368 .
992 .
752 c.
496 .
384 .
496 .
256 .
250 .
496 .
320 .
432 ,
448 .
480 .
576 .
816 .
1040 .
384 ,
656 .
784 .
880 .
304 .
416 .
480 .
320 .
320 .
976 .
592 .
416 .
352 .
336 .
448 .
400 .
560 .
304 .
624 .

A. Maple 6.

., . "" PC ( )
., . Visual C++ MFC,
2- ( )
. Web- MS Office 2000
,, .

., . Microsoft Access 2000:
. . Microsoft Office 2000:
. Access 97 ( -)
. .

., . IP-
. . -
Delphi { )
. Visual LISP AutoCAD
. ActiveX Delphi
. Adobe InDesign:
. Windows Scripting Host
. 3D Studio MAX 3.0
( -)
.
., . PC: , ,
2-
. .
. SVGA- IBM
. Photoshop Plug-Ins
. MS SQL Server 2000:
. SQL Server 7.0:
.
Visual C++ ( )
. ATL 3.0 ( )
., . ADO Delphi { -)
. , , Web Linux
A. Windows 2000 Active Directory
. Java ( -)
. Web-
. -
. Web-. XML
. C++
., .
. , , ( -)

528 .
720 .
1040 .
320 .
560 .
832 ,
680 .
656 .
512 .
512 .
432 .
576 .
320 .
544 .
320 .
352 .
512 .
336 .
352 .
432 .
464 .
368 .
370 .
256 .
928 .
816 .
416 .
400 .
400 .
224 .
224 .
304 .
416 .
464 .

" BHV"
. Internet , 2-
A. Adobe Photoshop 5.0 { )

752 .
448 .

""
., , Visual Basic 6.0
.
. VBA
. .
. JavaScript
. Excel 2000 { )
. Macromedia Dreamweaver 4
. Macromedia Flash 5
., . : , ,
( )
. Adobe Premiere 6.0
. MathCAD 2001
. Microsoft Internet Explorer 6.0
. 4
. Object Pascal
Delphi 6 ( }
. .
Turbo Pascal 7.0 Delphi, 2- ( )
. UML
., . Perl
., . Microsoft FrontPage 2002
., . Windows 2000 Professional
., . Windows Millennium
. 3D Studio MAX 4.0
. AutoCad 2000 Visual LISP,
2-
. AutoCAD 2002
. Kylix
. Visual C++ 6 ( )
. #
. WML WMLScript
. ., . . Adobe Photoshop 6
( )
. ., . . CorelDRAW 10
. MFC ( )
. Java
. Microsoft Word 2002
. .
. HTML 4
. C++, 3- ( )

624 .
448 .
512 .
640 .
512 .
368 .
560 .
368 .
480 .
432 .
544 .
288 .
576 .
528 .
416 .
304 .
432 .
576 .
528 .
464 .
370 .
672 .
608 .
416 .
960 .
576 .
240 .
608 .
640 .
640 .
464 .
624 .
272 .
288 .
512 .

" "
. PC
. Web-
. Web-

352 .
512 .
288 .

.
., . PC
., . PC
., . PC. Cakewalk Pro Audio 9.

., . PC, Cakewalk.
""
., . .

., . PC

320 .
272 .
256 .
420 .
272 .
608 .
240 .

" "
.
( -)
.
. ,
2-
, C/C++
, Turbo Pascal
.
. Unix
.
, .
, .
MOTOROLA
.
.

464.
240 ,
512 .
288 .
256 .
432 .
528 .
224 .
464 .
512 .
528 .
592 .

""
,
.
. ,

304 .
288 .
304 .

" "
. .
., A. Delphi.
. JavaScript.
. Microsoft Excel.
., . Microsoft Access,

480 .
288 .
336 .
208 .
304 .