You are on page 1of 160

004.

43
32.973.202
49

++
,

49

. .
++. / . . 
. 2 . .: , 2006. 320 .
ISBN 5964300286

C++ ,
AT&T. C++ ( , , with classes)
Simula ( ,
1967 ). , , C++,
; 
,
.
C++ (
) . ++
 ( 
, , ) 
.

++. , 
.
004.43
32.973.202

ISBN 5964300286

. ., 2006
, 2006

317

318

24. . . . . . . . . . . . . . . . . . . . . .68
25. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70
26. . . . . . . . . . . . . . . . . . . . . . . . . . .75
27. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .76

1.
++

2. ++
1. . . . . . . . . . . . . . . . . . . . .78

1. ++
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3

2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .79

2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6

3. TURBO C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .79

3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10

4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .80

4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11

5. ,
 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .87

5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12
6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13
7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13

6. ,
. . . . . . . . . . . . . . . . . . . . . . .91

8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13

7.
. . . . . . . . . . . . . . . . . . . . . . . . . .95

9. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14

8. . . . . . . . . . . .95

10. LVALUE () . . . . . . . . . . . . . . . . . . . . . . . . .15

9. . . . . . . . . . . . . .96

11. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15

10. . . . . . . . . . . . . . . . . . . . . . . . . . . . .98

12. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17

11.
, define
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .100

13. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18
14. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .31
15. . . . . . . . . . . . . . . . . . . . . . .31
16. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .34
17. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .39
18. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .51
19. . . . . . . . . . . . . . . . . . . . . .58
20. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .59
21. As . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .60
22. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61
23. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .66

3.
1.  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .103
2. STLport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .104
3. Microsoft: C# . . . . . . . . . . . . . .106
4. C++ Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .108
5. . . . . . . . . . . . . . . . . . . . . . .111
6. . . . . . . . . . . . . . .116
7. . . . . . . . . . . . . . . . . . . . . . . . . . . . .122
8. . . . . . . . . . . . .126

319

9. goto . . . . . . . . . . . . . . . . . .132

10. . . . . . . . . . . . . . . . . . . . . . . . . . . .136
11. . . . . . . . . . . . . . . . . . . . . . . . . . . . .141
12. gets() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .143
13. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .146
14. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .149
15.  . . . . . . . . . . . . . . . . . . . . . . . . . . . . .154
16. . . . . . . . . . . . . . . . . . . . . . . . . . .158



++

17. ploticus . . . . . . . . . . . . . . .161


18. . . . . . . . . . . .164
19. C/C++ EMX Watcom . . . . . . . . . .183
20. #import . . . . . . . . . . . . . . . . . . .188
21.
Windows Borland C++ Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .204
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .214

. .
 . .
 . .
. .
. .
. .
. . , . .
07.05.2006. 60x90/16.
. . .
. . 20. 3000.

++

1.

++
1.
++

C++ , 
AT&T. C++ ( , , with classes)
Simula ( , 
1967 ). , (
C++), ; ,

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

, , Modula2 Ada, .
, C++.
, C++
, , . ,
( ) cfront, 
, C++
. , ,
; , C++
.
C++, ,
 .
,
, ;


++

GTK+, 
 . 
,
( ) 
, .. ,
.
,
( , 
), C++, , 
 .
, (
, 
, ),
main() .. , C++ ,
, , ( , , 
) ( 
). , C++
( ) . ? 

 ( , 
, )
.
(.., , ,
,
), 
. 
 . ,
,
C++ 
.
C++
, , , 
. , 
, , ,
( ),
. , 
, ( ,
) ( 
)
. ,
STL (
std::cin std::cout).

++


++. ,

( ),

,
 .
C++ C*,
, inline, ,
, , , 
, .

, 

, ,
, 
.


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

++
;

++ ;

++

;

++

++ ;


, ..

, ;

++ ,

.

2.

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

, ,
. 
, ,
, .

/* , 
*/. .
// ,
, .

()

; ; '_' 
; .

++



:

asm

auto

break

case

char

class

const

continue

default

delete

do

double

else

enum

extern

float

for

friend

goto

if

inline

int

long

new

operator

overload

++

public

register

return

short

sizeof

static

struct

switch

this

typedef

union

unsigned

virtual

void

while

signed volatile 
.

.
, .

, , 
, 0 ( ),
. 8 9 .
, 0 0, 
.
f F,
10 15.
,
, (long);
, 

++

, long; 
int.

, ,
l ( ) L, 
.

, 
(), , , ''. 

().
int.
, ' \,
escape
:

NL(LF)

\n

NT

\t

VT

\v

BS

\b

CR

\r

FF

\f

\\

() '

\'

0ddd

\ddd

0xddd

\xddd

Escape \ddd , 
1, 2 3 , 
. \0
( ), NULL.
Escape \xddd ,
1, 2 3 , 
.
, .

10

++


, 
, , (,
, ). 
. ( )
; , () 
( ) . 
double.

, , 
int.


. 
*const; ,
, const.

, 
: ....
static, .
()
\0 , 
.
"
\; , escape
, .
, ,
\; , \ , .

3.



, 
.

++

11

. 

opt, { opt} 
.


() , , ,
. . 
,
. , .

12

++

, , ,
.

.
, .
,
::.

. , 
. , ,
, .

, , ,
, class, struct
union. enum, ,
, ,
enum.

4.

5.

: , , 
.

, ,
, , 
extern (1)
, .

, , 
.
,
, . 
,
.

, , 
, , .


,
,
>.

:: , 
.

6.

, static,
. 
. , 
.

, , , 
.
,
. ,
, inline const, ,
, 
.

++

13


.
, const, 
, const,
extern .
inline.

7.

:


.

.

new delete.

8.

, (char), 
, 
, 
.
,
short int, int long int. (long int)
, (short int), 
, , 
.
, 
; ,
.

14

++

.
enum int. ,
unsigned, 2n, n
.
(float) (double)
.

, 
.
char, int enum 
. float double
.
void () .
() void
, , .

,
.
void.

9.


, 
:

,
;

, ;

,
,

;

++

15

,
;

, ,
.


.
void* ( void) 
.

10.
LVALUE ()
; lvalue () , 
. 
.
, : ,
, * ,
, .
lvalue 1=2,
1 (value) .
,
.

11.

, 
. .

; . 
, 
. unsigned char
0  .
,
(), ASCII .

16

++

, , esc

; , '\377' 1.
char,
; .

Float doubl
float
. 

, .



. , 
. 
, 
.

.
, .



; ,
.

; int long
.

Unsigned

unsigned unsigned.
,
(mod 2**( )) (.. 2**( )).

,
.

++

17


. ,
.

12.



.
.
, char, unsigned char short 
int.
, double, 
double .
, unsigned long,
unsigned long .
, long, 
long .
, unsigned, 
unsigned .
int 
.


, , , 
.. .

0 ,
, ,
.

void*.

18

++

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


, , 
.

.

13.

, 
, . 
.

( 
).
. 
. , 
, ,
.
. 
,
(*, +, &, |, ^), ,
;
.

. 
C++ ; 0


.
, 
, ,
, .

++

19


, 
. __ 
.
::, 
, , .
,
.
Typedef, ::, 
, . Typedef 
, .
.
Typedef , 
. typedef
.
.
int, long double .
. 
. 
.
this 
. ,
.
, ,
, ,
. , lvalue
.
, 
, .
. ..., 
int ....
1[2] ( )
*((E1)+(E2)).
,
, (, )
, 
. ,

20

++

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

.
.
, 
,
.

, .
float, 
, double; , , 
.
; . 
.
, ,
( , typedef
::) .
,
.
,
, .
, 
.
, (>), 
( , typedef
::) .
,
.
, , 
.
, E1>MOS , (*E1).MOS. 
..., 
, . 
.


* :
lvalue, 

++

21

, . 
..., ....
& ,
. lvalue. 
..., ....
+
.
.

. .
.
2n, n
int.
! 1,
0, 0, 0.
int. .
~ . 
.
.


++ .
. ,
. ++x x+=1. 
.
 
++.
, ++,
. .
, , ,
++. , 
.
, ,
. . , 
, , 
++. , .

22

++

Sizeof
sizeof . ( 
, sizeof.
, 
, char).

. , 
.
,
.
sizeof 
. , , 
.


__, , ,
( _,

) .
, 
, _ . 
, .
.

, . , int
long , .
, , 
, .

. ,
, ,
.

.
, 
,
.

++

23

,

. 
.
,
 .

.
&X,
X*.


new _, 
. , new,
, . new
.
,
. , new int new int[10] int*.

. new :
void* operator new (long);
. 
. operator new() 
, .
delete , new.
void. delete , 
new. delete ,
new.
delete .
, delete

void operator delete (void*);



delete [ ]
,
.
.

24

++


*, / % .
.
:
*
/
%
* . * 

.
/ . 
0, 
, 
.
, ,
, . , (a/b)*b + a%b 
a ( b 0).
%
. .
.


+ . 
.

, .
:
+

+ . 
. 

, .
, 
, 
. , P
, P+1 

++

25

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

int, long.
,
, 
, , ,
, .

26

++


() ,
 : a < b < c , .
:
<
>
<=
>=
< ( ), > ( ), <= >= 0, 
, 1, .
int.
.
; 
, , 
. 
.


<< >> . 

, .
int; 
. ,
.
:
<<
>>
1 << 2 1 (
), 2 ; 
. 1 >> 2 1,
2 .
, (
), 1 unsigned;
( ).

==
!=
== !=
. (, a < b == c < d 1 ,
a < b c < d ).
0.


:
&
& , , &, 
. 
; .
.

++

27

28

++

^
^ , , ^, 
. 
;
. .


:
|
| , , |, 
. 
; 
. .


:
&&
&& . 1,
, 0 .
& && ;
, , 0.
,
.
int.

? :
. 
, 0, 
, .
,

.
,
. 
.


, 
. lvalue, 
, . lvalue 
( , const).
,
.
:
_
_ :

+=

=

*=

/=

%=

>>=

<<=

&=

~=

||
| | . 1, 
, 0 . 
| | | 
; , ,
0.
,
.
int.

++

29

|=

=
, .
, 
.
,
,
.
. 
.
... 
, .
E1 op= E2
E1 = E1 op (E2); E1 .
+= = ,
() , 
;
.


:
,
, , 
, . 
.
.
, , 

, , , 
.
:
f (a,(t=3,t+2),c)
, 5.


, ,
, . 

30

++

.
.
= & () 
.
, (
, ++a a+=1), 
, . , 
, , ,
lvalue; ,
.


, , 
, ,
, ,
.
, @, x@ @x 
x.@() @(x).
++  
.



, , ,
, . ,
@, x@y
x.@(y) @(x,y).


:
_ (_ opt)

_ []
.
operator() operator[]. x(arg) 
x.operator()(arg) x. 
x[y] x.operator[](y).

++

31

14.

, 
; ,
. :
_ opt _ opt;
_
asm_
_ , 
. _

.
, , _
class_ enum_.

.

15.

(sc) :

auto

static

extern

register

, auto, static register


, 
. extern 
,  
.
register auto (
) ,
. .
&.

32

++

auto register 
, , .
, 
.
sc_.
sc_, 
. 
: .
static extern
.

:

overload

inline

virtual

overload 
.
inline ,
.
, ,
inline 
. , ,
inline . virtual 
.
friend

. typedef .


(_) :
_:
__
class_
enum __
const
const 
_. 

++

33

_. const lvalue.
, int.

34

++

, 
__ _.

__ :

char

short

int

long

unsigned

float

double

const

void

long, short unsigned 


. int; unsigned 
char, short long.
__ :

typedef

class

struct

union

enum


, 
.
:
class x { ... };
void f(int x)
{
class x a;
// ...

16.

_, ,
,
.
_:
_
_ , _
_:
opt

, .
:
:
_
( )
* const opt
& const opt

( __ )

[ _ opt ]
:
__
typedef :: __
__ :

typedef
~ typedef
__
__
, .

++

35


, 
, , ,
.
_; 
. ,
_ .

, , , 
. 
, .
:
T D1
T ( int ..), D1 . ,
... T, ... 
, D1 (
x int x int). , D1
*D
... T
D1
* const D
...
T, , , *D, lvalue.
D1

36

++

__ , _
_
_:
_
_ =
_ _
_ _ =
__ ,
, 
; , 
.

, .
__ 

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

&D

D1 :

D[_]

& const D
... T.
lvalue, const 
. void (void&).
D1
D (__)
... ,
__ T.
__:
__ opt ... opt
__:

D[]
... T.
_ , 
, int.
, 
; , 
, 
.

++

37

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

:
int i;
int *ip;
int f ();
int *fip ();
int (*pfi) ();
i, ip , f, 
, fip, , pfi
, .
. *fip() *(fip()), ,
, fip, 
() .
(*pfi)() ,
, ,
, ;
.
f fip , fip
, .
:
const a = 10, *pc = &a, *const cpc = pc;
int b, *const cp = &b;

a:

38

++

pc:

cpc:

b:

cp: .

a, cpc cp 
. pc , , cp.

:
a = 1;
a++;
*pc = 2;
cp = &a;
cpc++;

:
b = a;
*cp = a;
pc++;
pc = cpc;
:
fseek (FILE*,long,int);
, .
, ,
int.
:
point (int = 0,int = 0);
, , 
int.
:
point (1,2);
point (1) /* point (1,0); */
point ()
/* point (0,0); */
:
printf (char* ... );
, 
.

++

39

40

++

opt:

printf ("hello, world");


printf ("a=%d b=%d",a,b);
printf ("string=%s",st);
, char*.

public opt typedef


:

,
float fa[17], *afp[17];

.
, ,
static int x3d[3][5][7];
, 3x6x7.
:

x3d ;

x3d, x3d[i], x3d[i][j], x3d[i][j][k]


.
, int.

17.

. typedef, 

. .
:
_ { _ opt }
_ { _ opt public :
_ opt }
_:
rr opt

class

struct

union

, . 
,
. : , ,
, , .
,
.
:
_
_ opt
_:
_ opt _;
_:

opt :
_
, , 
. ,
cl cl,
cl. 
.
:
struct tnode
{
char tword[20];
int count;
tnode *left;
tnode *right;
};
20 ,
.

++

41

,
tnode s, *sp
s sp
.

sp >count
count , sp;
s.left
s;
s.right >tword[0]
tword s.


 static;  .
auto, register extern.
,
. mem cl cl:mem,
. ,
cl.

C
, , ( friend) 

.
:
struct tnode
{
char tword[20];
int count;
tnode *left;
tnode *right;
void set (char* w,tnode* l,tnode* r);
};
tnode n1, n2;
n1.set ("asdf",&n2,0);
n2.set ("ghjk",0,0);

. , 
. 

42

++

, 

typedef . __
:
void tnode.set (char* w,tnode* l,tnode* r)
{
count = strlen (w);
if (sizeof (tword) <= count) error ("tnode string too long");
strcpy (tword,w);
left = l;
right = r;
}
tnode.set , 
tnode.
word, count, left right.
, 
. , n1.set(...) tword n1.tword,
n2.set(...) n2.tword. 
, strlen, error strcpy 
.
this , 
. this , 
cl, cl*.
mem cl, mem this>mem
cl ( mem
).
. 


inline .
:
int b;
struct x
{
int f () { return b; }
int f () { return b; }
int b;
};

++

43

int b;
struct x
{
int f ();
int b;
};
inline x.f () { return b; }

overload: 
, .

. (...),
, . 
, 
.



rr :public opt typedef
typedef , 
, . , 
.
, 
, ,
; 
:
typedef ::
:
struct base
{
int a;
int b;
};
struct derived : public base
{
int b;
int c;
};
derived d;

44

++

d.a = 1;
d.base::b = 2;
d.b = 3;
d.c = 4;
d.
.


base () virtual
vf, derived vf, vf
derived derived::vf.
:
struct base
{
virtual void vf ();
void f ();
};
struct derived : public base
{
void vf ();
void f ();
};
derived d;
base* bp = &d;
bp >vf ();
bp >f ();
, , derived::vf base::f
derived, d. 
, ,

, .
, 
, , 
.
, 
, 
. (friend).
f , , 
f, .

++

45

. 
, , 
.
, , 
.

, , 
. 
; .
, 
:
typedef ( _ opt )
:
complex zz = complex (1,2.3);
cprint (complex (7.8,1.2));
, , ( 
, zz ),
, .
.
, 
,  .
overload, virtual friend.
, 
.
, , 
, 
.
,
, ,
.

, , 
. 

.

46

++

X ,
X, X , 

.

.
:
class X { ... X (int); };
f (X arg)
{
X a = 1;
/* a = X (1) */
a = 2; /* a = X (2) */
f (3); /* f (X (3)) */
}
X ,
, 
,
X.
:
class X { ... X (int); };
class X { ... Y (X); };
Y a = 1; /* : Y (X (1)) */

cl ~cl .

; cl 
.
overload, virtual friend.

. 
.


, class, 
, , 
, public:.
.

++

47

.
, .

public, 
; , 
.
mem base 
:
typedef . ;
typedef ,
.
.
:
class base
{
int a;
public:
int b,c;
int bf ();
};
class derived : base
{
int d;
public:
base.c;
int e;
int df ();
};
int ef (derived&);
ef c, e df.
derived, df b, c, bf, d,
e df, a. base, bf 
a, b, c bf.

(friends)
, 
. 
:
class private
{

48

++

int a;
friend void friend_set (private*,int);
public:
void member_set (int);
};
void friend_set (private* p,int i)
{ p >a=i; }
void private.member_set (int i)
{ a = i; }
private obj;
friend_set (&obj,10);
obj.member_set (10);
friend 
, 
. cl1
cl2
class cl2
{
friend cl1;
. . .
};

C
,
.
__: operator op
op:

&

++

49

50

++

<

, . , :

>

+=

=

*=

/=

%=

^=

&=

|=

<<

>>

<<=

>>=

==

!=

<=

>=

&&

||

++



()

[]

.
,
.

struct s { ... };

class s { public: ... };


(
).

, 
0, 
.

.
( 
).

opt: _
; .
;
. , , 
. .
, 
.
().
0 
. 
, . ,
unsigned.
unsigned.
&,
. .

++

51


. 

. 
,
.


.
:
int x;
class enclose /* */
{
int x;
class inner
{
int y;
f () { x=1 }
...
};
g (inner*);
...
};
int inner; /* */
enclose.g (inner* p) { ... }
x f x,
enclose. y inner, g 
. g enclose, , 
g, enclose.
inner g
inner, int.

18.


. =, 
, .

52

++
:

= expression
= { _ }
= { _ ,}
( _ )
_:
_,
_
{ _ }

,
,
.

, , 
.
, 

. (
), , , 
.
; 
, .
, () , X
a(); X, ,
X.


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


++

53

; , , , 
.
, ,
, , 
,
.
,
int x[] = { 1, 3, 5 };
x ,
, .
float y[4][3] =
{
{ 1, 3, 5 },
{ 2, 4, 6 },
{ 3, 5, 7 }
};

: 1,3 5 y[0], , y[0][2].
, y[1] y[2].
, y[3]
0.
float y[4][3] = { 1, 3, 5, 2, 4, 6, 3, 5, 7 };
y ,
y[0], 
. ,
y[1] y[2].
float y[4][3] = { { 1 }, { 2 }, { 3 }, { 4 } };
y (
) .



, ; 
. , 
, , 
.

.

54

++
:

struct complex
{
float re;
float im;
complex (float r,float i)
{ re=r; im=i; }
complex (float r) { re=r; im=0; }
};
complex zz (1,2.3);
complex* zp = new complex (1,2.3);

; .
:
complex zz1 = complex (1,2.3);
complex zz2 = complex (123);
complex zz3 = 123;
complex zz4 = zz3;

,
, .
, , 

.
.

, 
.

T&, T,
T,
T. 
&.
:
int i;
int& r1 = i;
int& r2 = &i;
r1 r2 i.

++

55

,
. 
.
:
r1 = r2;
, r2, , 
r1.
. ,
.
pp, ,
rr, pp=&rr. :
pp=&*rr
T
,
T.
. , ,
, .
:
double& rr = 1;
, rr double, 
1.0.
.



char. 
.
:
char msg[] = "Syntax error on line %d\n";
,
.


(
sizeof new) . 
, 
, .

56

++
:

_ _
_:

*
_
_ ( _
_)
_
[ _ opt ]
( _ )

_, ,
.
, .
:
int
int *
int *[3]
int *()
int (*)()
, , , ,
, , ,
.
, 
.
__:

typedef

char

short

int

long

unsigned

float

double


.

++

57

:
(double) a

double (a)

typedef
, _ typedef, 
, , 
,
. :
typedef :

, typedef, 
,  ,

, , .
typedef.

58

++
:

rr
;
enum ;
, (
, ) .
, .
:
class vector;
class matrix
{
...
friend matrix operator* (matrix&,vector&);
};
class vector
{
...
friend matrix operator* (matrix&,vector&);
};

,
typedef int MILES, *KLICKSP;
struct complex { double re, im; };

19.

MILES distance;
extern KLICKSP metricp;
complex z, *zp;
; distance int, metricp
int.

, (
) , .

typedef , , 
. 
distance
, int .
.
:
struct X { int a; };
struct Y { int a; };
X a1;
Y a2;
int a3;
.



.
&.

char>short>int, int>double,
int>long float>double.
,  over
load .
:
overload abs;
int abs (int);
double abs (double);

++

59

60

++

,
,
.

=,
0 1 
.

, abs(12) abs(int), abs(12.0)


abs(double). , 
abs(double).

=
; 
.


,
, ( 
,
) .


.
.

:
class X { ... X (int); };
class Y { ... Y (int); };
class Z { ... Z (char*); };
overload int f (X), f (Y);
overload int g (X), g (Y);
f (1); /* : f(X(1)) f(Y(1)) */
g (1); /* g(X(1)) */
g ("asdf"); /* g(Z("asdf")) */

.

20.

int .
enum_:
enum opt { enum_ }
enum_:

enum_,
:

= _
enum
, .

enum_
; 
.
:
enum color { chartreuse, burgundy, claret=20, winedark };
...
color *cp, col;
...
col = claret;
cp = &col;
...
if (*cp == burgundy) ...
color , , 
cp . 
{ 0, 1, 20, 21 }.

21.
As
Asm :
asm ();
asm .
.

++

61

22.


, 

;

.

,
( , 
) ,
:
_:
{ _ opt _ opt }
_:

_
_:

_
 _ 
,
, .
auto register 
. ;
. ,
static
.


:
if ( )
if ( ) else

62

++

, ,
.
, 0. ,
else , else
if, else.

whil
while :
while ( )
, 
. 
.

d
do :
do while ();
,
. 
.

for
for :
for ( _1 opt ; _2 opt ; _3 opt )

:
_1;
while (_2)
{ _3; }


,
, ;

,
.

. 
_2 while
while(1); 
.

++

63

switch
switch 
.

switch ( )
.

case :
case _ :
_ 
; 
. switch , case,
.

default :
switch, 
case .
,
, case.
case ,
default, ,
.
case default ,
switch .
case default 
, , 
.
switch . 
, 
.

break

break ;
while, do, for
switch ; , 
.

64

++

continue

continue ;

while, do for;
. ,
while (...)
do
for (...)
{
{
{
...
...
...
contin:;
contin:;
contin:;
}
}
}
while (...);
continue goto contin ( contin: ).

return

return, :
return ;
return ;
, 
, .. void.
, 
;
.
, ,
, , .
return 
.

++

65

goto


goto ;
,
.

:
. 
goto.
,
, .



;

} , 
, while, .

delete
delete
delete ;
. , 
, . , 
delete ,
.
delete , 
new, . , 
.

as
asm
asm ( ) ;

66

++

asm .
.

23.

C++ 
.
static . 
, int.

, , , 
. ,
, , 
( ) .


:
_:
_ _ opt _
_
opt _
(sc
), ,
extern, static, overload, inline virtual.
,
..., , 
.
:
_:
( __ )
, , ,

, , .
,
.

++

67


_:
_
:
int max (int a,int b,int c)
{
int m = (a > b) ? a : b;
return (m > c) ? m : c;
}

int ;

max (int a, int b, int c) ;

{ ... } , () .

(, 
) 
, ,
..., , ....
:
__:
: ( _ opt )

.
:
struct base { base (int); ... };
struct derived : base { derived (int); ... };
derived.derived (int a) : (a+1) { ... }
derived d (10);
d 
11.


:
_:

68

++


, 
, ( ), 
.

24.

C++ , 
, 
. , #, .
; 
, 
( ) 
.
, const inline
#define.


:
#define _

, . ( 
) .
:
#define ( , ..., ) _
, 
. 
(, 
, , ), ,
.
,
, 
. , 
; , ,
.
.

++

69

,
( 
define) .

. 
\
.
:
#undef
.


:
#include "_"
_.

, .

70

:
#ifdef
, 
; , #define.
:
#ifndef
, 
.

, ,
#else

#endif
, #else
#endif . ,
#else , #else, #endif, 
.

. :
#include <_>
,
. (, 
, .)
#include .


:
#if
, . 
. 
:
sizeof
.

defined.
,
#define #undef;
0.

++


,
C.
:
#line "_"
, , ,
, 
.
, .

25.

, 
.

++

71

,
. 
, , , , 
.

, :
.
,
. ,
typedef int (*PF) ();
extern g (PF);
extern f ();
...
g (f);
g :
g (PF funcp)
{
...
(*funcp) ();
...
}
, f 
, g(f) (.

72

++

, , 
, *, (n1)
, ,
.
:
int x[3][5];
x 3 5. x 
, ( ) 5
. x[i], *(x+1), x 
, , , 1 x,
1 ,
, 5 .
,
( 5 ), 
.
, ;
.
,
( ), 
,
, .


, , 
, .
.

,
, . 
. 
[] , E1[E2]
*((E1)+(E2)).

, 
. , int long , 
.
, , 
, .

, +, E1
E2 , E1[E2] E2 E1. ,
, 
.

.
, 
, , 
.


. E n i*j*...*k,
E (n1)
j*...*k.


.
, , 
.

++

73

,

.
, , , 
( ) char;
.
extern void* alloc ();
double* dp;
dp = (double*) alloc (sizeof double));
*dp= 22.0 / 7.0;
alloc ( ) ,

double; . 

.
,  .


C++ , 
: , case , 
,
.

, , , ,
sizeof , , :

&

<<

>>

74

++

==

!=

<

>

<=

>=

&&

||

, 
.

; , , 
, 
& ,
, 
. & 
.
,

.

#if: , , sizeof
.

++

75

26.

C++ 
.
, 
, , ,
, . 
.
, (
) 
, ,
.
.
,
, , 
. , 
;
register .

. ,
 , .
.
, .

.

int, 
. ,
, , 
. 
, .
,
(, int char
, ), 

.

76

++

27.

new
extern void* _new (long);
. .
. _new 
, .
delete
extern void _delete (void*);
, , 
. _delete() ,
_new(), , 
_delete() . 
delete .
_new() _delete(), 
,
.
new ,
() 
new.

this  
.
this

.
:
class cl
{
int v[10];
cl () { this = my_own_allocator (sizeof (cl)); }
~cl () { my_own_deallocator
(this); this = 0; }
}
this , 
(
), .

++

77

this, 
( )
,
.

78

++

2.
++


this, ( 
) .

1.

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

().
, TURBO C++ 
, 
:


,
.

(
HELP
EDIT).

: 
, 
.
.

++

79

2.


. 
, 
.

3.
TURBO C++
, TURBO C++,
. , 
, , ,
, .
TURBO C++ ,
. 
, .
, , 
.
, 
:


, , 
:


,
.

80

++



, ,

.

, .


, 
,
.

: , 
, , .

4.

()
. 
ALT+. :

About

,
TURBO
C++. ESC ENTER.

Clear Desktop

. 
, .

Repaint Desktop

++

81

Transfer
, 
Transfer,
Options/Transfer.
.

File (ALT F)
EDIT
, ,
, DOS
TURBO C++.
Open (F3)
FILE OPEN , 
, EDIT.
, ,
OPEN, REPLACE, CANCEL HELP, .
:

REPLACE
OPEN.

Open Edit.
Replace Edit; 
Replace .

.

.

,

.

,
.


DOS (* ?).
Enter, Turbo C++ . , 
Turbo C++ , 
.

82

++

?, ,
,
, .
New
File New Edit 
NONAMExx. ( 
00 99).
NONAME
;
, Turbo C++ .
Save (F2)
File Save , 
Edit ( Edit , ,
).
(NON
AMEOO.C ..) TurboC++ Save Editor File, 

.
Save As
File Save As
Edit , .
Change Dir
File Change Dir
, . 
, Turbo C++ 
. Options Directories
.
Print
File Print Edit Turbo
C++ (
), ,
DOS.
,
. 
CtrlK P.

++

83

Get Info
File Get Info , 
.
DOS Shell
File DOS Shell Turbo C++,
DOS .
Turbo C++ EXIT Enter.
, 
.
Run Program Reset (CtrlF2).
Quit (AltCx)
File Quit Turbo C++, 
DOS. ,
, Turbo C++ 
.

Get Info
Current directory
.

84

++

Total time
.
Program loaded
.
Program exit
.
Available memory
DOS (640 ).
Last step time
.

Edit (AltCE)
,
Edit.
. 
:

Shift .

CtrlK B,
.
CtrlK K.

CtrlK L.

, Edit,
(Clipboard).
Edit.

Current file
.
Extended memory usage
, Turbo
C++.
Expanded memory usage
, Turbo C++.
Lines compiled
.
Total warnings
.
Totals errors
.

Restore Line

,  . 
.
Cut (ShiftCDel)

.
Paste.

++

85

Copy (CtrlCIns)
, 
. 
Paste. Help; 
Shift .
Paste (ShiftCIns)

.
Show Clipboard
Clipboard, 
, .
Clear (CtrlCDel)
,
. ,
.

Search (AltCS)
Search , ,
.
Search Find
Search Find Find, 
,
.
CtrlQF.
Replace (Ctrl Q A)
Search Replace 
, .
Search Again (Ctrl L)
Search Again Find
Replace. , 
(Find Replace),
.

Run (AltCR)
, 
.

86

++

Run (CtrlCF9)
Run , , 
Run Arguments.
race Into (F7)
. 

, .
, 
.
Program Reset (CtrlCF2)
Run Program Reset ,
, 
.
Over
Run Step Over
,
.
Step Over , 

.
Arguments
Run Arguments
,
DOS. / DOS
.

Compile (C)
Compile 
, 
.
EXE File
Compile Make EXE File
EXE.
Link EXE File ( )
Compile Link EXE File OBJ LIB
, .

++

87

Debug (Alt F9)


Debug 
.
Inspect (Alt F4)
Debug Inspect Inspector, 
.

Options (AltCO)
Options , 
, 
Turbo C++.

5.
,
C
Main
++ ()
main.
, main, 
{}.
main :
main()
{
/* , main */
}

88

++

, 
, 
.

Include
++ 
, main.

#include <_1>
#include "_2"
...
#include <_n>
,
_1, _2 , ... , _n .
<...>, 
. 
++ Include 
.

#define, 
, ,
++ 
.
,
#define pi 3.1415926
pi 3.1415926. 
(;) .

++, /* */, 
.

++ , 
, .

: 
. , , 
(.. 
), .

,
, .
:
float weight;
int exam_score;
char ch;

++

89


, , 
.
.
:
int height = 71 ;
float income =26034.12 ;
,
++,

char

int

long

float

double

90

++

% char
%s
%d int
%o int ( )
%u unsigned int
%x int ( )
%ld long ( )
%lo long ( )
%lu unsigned long
%lx long ( )
%f float/double (c )
%e float/double ( )

printf:
printf 
, , , ,
.
:
printf("\n %d. $%.2f",age,income);
, age () 
income ()  .
\n
.

. %d 
age.
$. %2f 
( ) ,

. income.

%g float/double ( f )
%lf long float (c )
%le long float ( )
%lg long float ( f )

scanf:
scanf , 
.
scanf 
.
&. .
:
#include<stdio.h>
main()
{
int weight, /**/ height; /**/
printf(" : ");
scanf("%d", &weight);
printf(" poc: ");
scanf("%d", &height);

++

91

printf("\n\n = %d, = %d\n",


weight,height);
}

6.
,

++ . 
, .
++ .
:


=.
:
c = a * b;
:
, b. ,
,
b.

.
,
if ( ( c = cube( a * b ) ) > d )
...
: ,
, .
.
++:

92

++

(sizeof)

().

(+)

()

(/)

(*)

(%).

( ) 
int, char, float. float.

.

(==)

(!=)

(<)

(<=)

(>)

(>=).

int.
,
, , .
 ,
, == !=.

++

93

.
.

&& (and)

|| (or)

,
char. 
, , , . ,
, .
, 
.
, , 
(),
.
(.. 
, int), 
(&&), ,

.
, 
(||), 
, 
.
,
:
if( i > 50 && j == 24)
...
if( value1 < value2 && (value3 > 50 || value4 < 20) )
...

94

++


.
, .

. .
:
a = ( b = c ) * d;
d , 
d, .
+=, =, *= /=
.
:
a += b a = a + b
a = b a = a b
a *= b a = a * b
a /= b a = a / b
++ 
() () 
.
:

++a
.

++
.

a
.

a
.

sizeof () ,
. ,
.
:


=, +=, =, *= /=,
++ .

printf ( "\n %d", sizeof( int) );


printf ( "\n c %d", sizeof( har) );

++

95

7.



.
++ (
), .

.

, void () .
, ,
.

96

++

.
.

9.

++ :

( )

(.. void),
, ( 
) .

, ,
.

, , 

. 
.

:
double cube( double x )
{
return x * x * x ;
}
double 
. extern, main,
, cube
main. extern ,
.

8.

++ 
.

(main). 

,
,
.

, , 
.
0 9
: a, b, c, d, e, f, A, B, C, D, E, F.
: 3478 ,
:
int a = 3478,
b = 06626,
c = 0D96;
l L,
, (long integer). 
u U, , , 
(unsigned long).

++

97

, 
. ,
, .


( )
,
.
1. 2e1
.1 2E1
1.0

.1234 .1e3
1.234 0.0035e 6
2e 1
2.1e 12 .234


().
++ int (),
ASCII.
,
, , 
esc,
, esc.
:

'\''

'\'

'\\'

98

++

\'

\"

\?

\ddd ASCII

\xhhh ASCII
.


, 
.
esc. 
.
:
# include <stdio.h>
main( )
{
char *str1, *str2;
str1=" \n\n";
str2="\ .\n\n";
printf(str1);
printf(str2);
}

esc 
.

\n

\t

\v

\b

\r

\f

\\

10.


.

 , 
.


,
, ().
(;), 

++

99

. 
(;).
,
.


(;),
. , 
, 
.

, , , 
.


if, if else, ?, switch go to. 
:
if ( )
;

if ( )
_1;
else
_2;

< > ? <_1> : <_2>;
,
_1, _2.

switch ( )
{
case _1:
__1;
break;
case _2:
__2;
break;
. . .
case _n:
__n;
break;

100

++

default:
__n+1;
}
default . ,
.


++ ,
: while, do while for. 
:
while( )
;


do
;
while ( );


for (, , _)
;

11.

,
define
, 
.
++ .
:
_ _ [ ];
, 
:
_ [ ]

, , , 
.

++

101

:
char name [ 20 ];
int grades [ 125 ];
float income [ 30 ];
double measurements [ 1500 ];
(name) 20 .
name [0], name [1],
..., name [19].
(grades) 125 .
grades [0], grades [1], ..., grades [124].
(incom) 30 . 
income [0], incom [1], ..., income
[29].
(measurements) 1500
.
measurements [0], measurements [1], ..., measurements [1499].
, (
array.):
#include <stdio.h>
#define size 1000
int data [size];
main ( )
{
extern float average (int a[], int s );
int i;
for ( i=0; i<size ; i++_)
data [ i ]= i;
printf ( "\n data =%f\n",average
(data,size));
}
float average (int a[ ] ,int s )
{
float sum=0.0;
int i;
for ( i=0; i<s ; i ++)
sum+=a[ i ];
return sum/s;
}

102

++

1000 .
average .
average 
. 
a.
size (). 
, ,
 .

103

3.

1.
C

, ,
, int
. .
:

() , ...

[] ...

* ...

, .
. ? (),
, , .... (
 , , , ,
...). [], .... 
,
) . ...
... . ? 
( (), [], *),
.  ,
, . ,
( ) ( .
, . (, 

.
:
int (*(*(*fptr)())[3])();
fptr ....

104


, ), :

int (*(*(*fun)())[3])();
fptr ....
, (. :
int (*(*(*fun)())[3])();
fptr , ... ),
. :
int (*(*(*fun)())[3])();
fptr , ...
(, . :
int (*(*(*fun)())[3])();
fptr ,
... ), . :
int (*(*(*fun)())[3])();
fptr ,
... (. :
int (*(*(*fun)())[3])();
fptr ,
, ... , 
:
int (*(*(*fun)())[3])();
fptr ,
, int.
, .

2.
STLport
STLport 

. , STLport 
,
, ,
Borland C++ 5.02 MS Visual C++ 4.0.
STLport 
, (
, 

105

106

). SGI (, 
, STLport). , STLport
SGI STL gcc sun cc. 
, , STLport 
, , , 
.

3.
Microsoft: C#

,
,
, , .
, ,
,  , 
. 
, ,
STL  .
, g++stl3 std::wstring. , std::basic_string
, std::string char,
wchar_t ( 
,  , c_str()
return "").

, 
Hello, world! C# Language Reference:

STLport 
. , debug
mode, , .
, 
. 
, .
, STLport ,
hash_map, . ? ,
map (

), ,  
, (, 
, ).

Microsoft , 
C++ Java, C# (C sharp).

using System;
class Hello
{
static void Main() {
Console.WriteLine("Hello, world");
}
}
Java. ,
:

>, , :
, ,
,
. ,
, C#
( , int, char, )
, , .

, Java, main
.

, Java, C#
, ..
.

,
, C#, Java,

. , ,
unsafe code,
.

object :
( )
object.

, . , STLport
,
. STLport SGI STL,
.
,  STL,
STLport , 
.

107

bool integer . char


Unicode ( , Java).

(
).

Java, C# goto.
foreach:
static void WriteList(ArrayList list) {
foreach (object o in list)
Console.WriteLine(o);
}
.
: checked unchecked. 

.

lock.
,
Java, . , 
, . , 
.
(property).
.

.
Java 
. , , C# 
, Java.
, , Microsoft
Java . ,
C++ .
Microsoft ,
web 
. ,
Microsoft C#.
, , . Microsoft, 
, ,

108

Java. Java Microsoft ,


C#. ,
, Java
,
, 
  
. 
C# , 
.
,
C# Java. , ,
Java 
, , Microsoft
. ,
Netscape , .

4.
C++ Builder
,
C++ Builder builder, ..
RAD (Rapid Application Development, ) ,
, 
.
, C++ Builder
Windows .
Yes, No,
Cancel WYSIWYG 
, , rtf.
C++ Builder 
: , , 
. 
, ,
: , , 
, .
, , 
. C++
Builder , , 
.

109

110

?.. : . 
,
, , 
...

C++ ; Delphi 
(, VCL
); .. ++ Builder :
C++ VCL.

? , ,

( ),
,
( 
), 
, , 
.

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

, 
, , , (, 
) 
. ,

. 
, 
.

web? 

, ,
, , 
. ,

, . , 
, ,
, .
, 
, 
. 
,
: , ..
,
C++ Builder . VCL (Visual Component Library),
Delphi, .. . 
,
, C++. 
, , VCL

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

, 
( ) 
.

, COM CORBA, 
CGI .. ,


: , 
.
, C++ Builder Delphi 
, .
Visual Basic, RAD
.
C++ Builder 
, , ,
C++ Builder  
. ,
, , , ,  , 

.

111

5.


C++. : , 
,
, 
>, 
. , 
:
class A {
public:
void method();
};
class APtr {
protected:
A* a;
public:
APtr();
~APtr();
A* operator >();
};
inline APtr::APtr() : a(new A)
{ }
inline APtr::~APtr()
{
delete a;
}
inline A* APtr::operator >()
{
return a;
}
,
APtr: aptr;
a:
aptr >method();

112

, operator>()
A* ( ), , , A&
,
A::method(), 
, 
.
, , : 
;
,

, ... ?
: 
.
, 

. , , : 
, (, ,
)
( 
),
.
: 
; ,
, , BoundsChecker.
, , 
: ,

. ,
(..,
 ), 
.

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

,
. : 

113

( ) 
...
. 
, . , 
.
,
, , 
, , , 
, malloc().
, 
.
,
, . ,
Java,
; , .

. , ,
:
template<class T>
class MPtr
{
public:
MPtr();
MPtr(const MPtr<T>& p);
~MPtr();
MPtr(T* p);
T* operator >() const;
operator T*() const;
MPtr<T>& operator=(const MPtr<T>& p);
protected:
struct RealPtr
{
T* pointer;
unsigned int count;
RealPtr(T* p = 0);
~RealPtr();
};
RealPtr* pointer;
private:
};

114

MPtr::MPtr(T* p),
. ,

 , MPtr::MPtr(), 
new .
,
,  . , 
, T

. 
MPtr ,
, . 
MPtr::MPtr(T* p) MPtr<T>
ptr(new T(a,b,c)) , .
: 
T*.  
.
MPtr 
,
:
template<class T>
class MCPtr
{
public:
MCPtr(const MPtr<T>& p);
MCPtr(const MCPtr<T>& p);
~MCPtr();
const T* operator >() const;
operator const T*() const;
MCPtr<T>& operator=(const MPtr<T>& p)
MCPtr<T>& operator=(const MCPtr<T>& p);
protected:
MPtr<T> ptr;
private:
MCPtr();
};
, () .
, , , operator> 
, . , ,
: ,
, (, 

115

, ) , 
(.., ; , 
). .
, MCPtr ( 
) : 
. , 
: const
.
,
(, , ):
.., , ,  
.
, ,
, (, 

).
,

. , ,
.
, 
. , , ,
: ,
... 
. ?
1, , .
,
, ,
. ? 
. , , 
.

, . 
,
.
COM
CORBA C++: 
,

.

116

( 
AddRef() Release()) COM.

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

6.

++, 
. . 
.
, 
: . 
, , 
, , , .
, SmartPointer? , 
... , :
class A
{
private:
int count;
public:
A(){count = 0;}
void addref(){count++;}
void release(){if( count == 0) delete this;}
protected:
~A();
public:
void do_something(){cout << "Hello";}
};

.
, ,
addref, , release. ?

117

118

. ,
. ? .

) . 
(, .

,

delete a release.

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


:
class PA
{
private:
A* pa;
public:
PA(A* p){pa = p; p >addref();}
~PA(){pa >release();}
A* operator >(){return pa;}
};
? PA, 
A 
. ? , 
?. ,
PA:
...
{
A* pa = new A();
pa >addref();
pa >do_something();
pa >release();
}
...
{
PA pa = new A();
pa >do_something();
}
... ?
. : ,
?. ,
PA
addref release A.  !
, ,
, (


.
Countable,
.
( 
 , , ,
:
class Countable
{
private:
int count;
public:
int increment ();
int decrement ();
};
, , , ,
, , 
..

:
class Lockable
{
public:
void lock();
void unlock();
bool islocked();
};
, 
, ,
.

119

:
class AutoDestroyable : public Countable
{
public:
virtual int addref ();
virtual int release ();
protected:
virtual ~AutoDestroyable();
...
};
,
.
,
.
template <class T>
class SP
{
private:
T* m_pObject;
public:
SP ( T* pObject){ m_pObject = pObject; }
~SP () { if( m_pObject ) m_pObject >release (); }
T* operator > ();
T& operator * ();
operator T* ();
...
};
, , 
.
,
, , delete
, .
, 
, .
SP,
,
. ,
. 
, ( ):

120

(
)
.

(
), ,
(
).

, , ,

.

, ,
SP. 
:
template <class T>
clacc MP : public AutoDestroyable
{
private:
T* m_pObj;
public:
MP(T* p);
T* operator >();
protected:
operator T*();
};
template <class T>
class H
{
private:
MP<T>* m_pMP;
public:
H(T*);
MP& operator T >();
bool operator ==(H<T>&);
H operator =(H<T>&);
};
? . MP 
, .. ,
. 
. , .

121

H SP,
, MP.


.
, 
.

: MP H
. ( MP
Lockable), .
, 
, 
( ).

122

 
. , TP
: 
, .
?
 :
class A : public B
...
TP<A> a;
TP<B> b;
a = new B;
b = (B*)a;
...
(
TP ):
template <class T, class TT>
TP<T> smart_cast ( TP<TT>& tpin );
,  ( 

PP TP:
class PP : public AutoDestroyable
{};
template<class T>
class TP
{
protected:
T* m_pObject;
PP* m_pCounter;

):
class A : public B
...
TP<A> a;
TP<B> b;
a = new B;
b = smart_cast<B, A>(a);
// Visual C++,
b = smart_cast<B>(a);
...

public:
TP ();
TP ( T* pObject );
TP<T>& operator = ( TP<T>& tp );
T* operator > ();
T& operator * ();
operator T* ();
bool operator == ( TP<T>& tp );
};
PP AutoDestroyable
. TP 
.

7.

H>MP>Obj, PP<
TP>Obj, .. ( , PP)

 C++ 
,

? , , 
static_cast dynamic_cast. ,
, .

123

. , , , 
, 
.
, :
class A
{
public:
virtual void f() = 0;
~A();
};
class B : public A
{
public:
virtual void f();
~B();
};
gcc :
g++ c Wall test.cpp
:
test.cpp:6: warning: `class A' has virtual functions but non vir
tual destructor
test.cpp:13: warning: `class B' has virtual functions but non
virtual destructor
, 
. , gcc ?
, C++
.., :
void call_f(A* a)
{
a >f();
}
, f()
, 
a. :
std::vector<A*> a_collection;
a_collection.push_back(new B());

124

, 
a_collection ( ,
RTTI). ,
:
for(std::vector<A*>::iterator i = ... )
delete *i;
, a_collection, ,
A.
, 
A B:
inline A::~A()
{
puts("A::~A()");
}
inline B::~B()
{
puts("B::~B()");
}
:
A* ptr = new B();
delete ptr;
:
A::~A()
A 
(virtual ~A();), :
B::~B()
A::~A()
, . , , 
. 

, 
 ; 
,
. , 

, , 
 ,
. :
#include <stdio.h>


class A
{
public:
A(const char* n);
~A();
protected:
const char* name;
};
inline A::A(const char* n) : name(n)
{ }
inline A::~A()
{
printf("A::~A() for %s.\n", name);
}
class B
{
public:
virtual void f();
B();
~B();
protected:
A a1;
};
inline B::~B()
{ }
inline B::B() : a1("a1")
{ }
void B::f() { }
class C : public B
{
public:
C();
protected:
A a2;
};
inline C::C() : a2("a2")
{ }

125

126

int main()
{
B* ptr = new C();
delete ptr;
return 0;
}
( 
), :
A::~A() for a1
, ?
B virtual. :
A::~A() for a2
A::~A() for a1

.

8.

, ,
. ,
,  
, , , 
.
,

,
. , , ,
.
, ?
:
struct data_item
{
type_1 field_1;
type_2 field_2;
// ...
type_n field_n;
};
data_item i1;

127

, , i1 , 
,
? :
FILE* f = fopen("file", "wb");
fwrite((char*)&i1, sizeof(i1), 1, f);
fclose(f);
assert ,
. , 
, .
, , . ,
:
FILE* f = fopen("file", "rb");
fread((char*)&i1, sizeof(i1), 1, f);
fclose(f);
? ,
. ,
, , , 
. , , 
( C++) () 
. ? , 
, ,
.
, 
. , , 
, ( 
, .. ), ,

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

( , sizeof
).
,
( , 
)
. ,

128

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

( 1, 
) , 
. 
,
#pragma. ,
#pragma pack, 
. :
#pragma pack(1)
struct { /* ... */ };
#pragma pack(4)
#pragma pack(4) , 
. ,

, ,
Win32
( MS Visual C++):
#pragma pack(push, 1)
struct { /* ... */ };
#pragma pack(pop)

, 1, 
. , gcc
win32 ( , , , Unix 
#pragma pack ). #pragma
pack(), ( msvc gcc),
.
, , . , 
. 
. inc.h:
#ifndef __inc_h__
#define __inc_h__
class Object
{

129

// ...
};
#endif // __inc_h__
, file1.cpp, file2.cpp
file2.h, . , file2.h
foo, () Object :
// file1.cpp
#include "inc.h"
#include "file2.h"
int main()
{
Object* obj = new Object();
foo(obj, "file");
delete obj;
return 0;
}
// file2.h
#ifndef __file2_h__
#define __file2_h__
#pragma pack(1)
#include "inc.h"
void foo(const Object* obj, const char* fname);
#pragma pack(4)
#endif // __file2_h__
// file2.cpp
#include "file2.h"
void foo(const Object* obj, const char* fname)
{
// ...
}

130

, . ?
(file1.cpp file2.cpp) 
(
, Object). ,
foo() main() (, 
, ). ,

, , , 
.
, ,
.
: , , 
,  , ,
, ,  
...
#pragma pack . , 
.
, ( 
, ).


. ,
/
, 
. :
template<class T>
inline size_t get_size(const T& obj)
{
return sizeof(obj);
}
, 
. ? , , sizeof
,  . 
, , , 
, , int. :
template<>
inline size_t get_size<std::string>(const std::string& s)
{
return s.length() + 1;
}
, , sizeof.

131

,
:
typedef unsigned char byte_t;
template<class T>
inline size_t save(const T& i, byte_t* buf)
{
*((T*)buf) = i;
return get_size(i);
}
template<class T>
inline size_t restore(T& i, const byte_t* buf)
{
i = *((T*)buf);
return get_size(i);
}
, (int float),
:
, ... , ,
save() . , 
, save()
. , 
:
template<>
inline size_t save<MyObject>(const MyObject& s, byte_t* buf)
{
// ...
}
. , save()
restore() ,
. , ,
. , save<long>()
htonl() restore<long>() ntohl(), 

... , . 
, ,

132

9.
goto
,

. ,
, , , 
goto , , .
, , 
, goto .
. goto ,

:
int i, j;
for(i = 0; i < 10; i++)
{
// ...
if(condition1)
{
j = 4;
goto label1;
}
// ...
for(j = 0; j < 10; j++)
{
// ...
label1:
// ...
if(condition2)
{
i = 6;
goto label2;
}
}
// ...
label2:
// ...
}

133

, goto 
, ,
. , ,
. , , 

, 
. , ,

. , 
do while; for 
, for
, 
(.., ). 
, for (.. ,
) 
. , ,  

( , ,  , 
, \\ ; , 
, , \,
, ). ,
.
 
,
, .
, goto. , 
(
, , , ) 
.
, goto
,
, . , ,
, , break,
. , 
, ,
, 
break (.., ,

). goto ( ),
, .

134

, ,
. :
switch(key1)
{
case q1 :
switch(key2)
{
case q2 : break;
}
break;
}
, , , .
,  break,
switch, break . ,
, , ( , 
break goto ), ,

(break , , goto).
:
bool end_needed = false;
for( ... )
{
for( ... )
{
if(cond1) { end_needed = true; break; }
}
if(end_needed) break;
}
.., , goto 
,
. , goto
, ; 
, . (
),
, (
) 
. ? ... , 
, , 
, , . ,
, 
... : .
.

135

goto :
int foo()
{
int res;
// ...
if(...)
{
res = 10;
goto finish;
}
// ...
finish:
return res;
}
, goto return 10 if.
, . ,
,
( IDEF). , 
... goto
, (
, ). ,
. , , 
 ( , 
). , , ,
. ? 
return , 
. ? , cut&paste.
? , search&replace. , 
.
, , 
. , C++
,
( ), 
. .
, .
, ( 
return
), assert 
. , .

136

goto 
, ,
, ( )
.
, 
goto . ,
/++ ( ,
), goto
.

10.

: , 
.
.
. ,
.
, 
. 
. . 
, ,
.
.
. 
, . 
. 
.
. . Ho
, .
He ( 
), 

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

137

( , ,
), . ( 
).
: envelope/letter (
) (
, ) 
. C++ ()
. . .:
class BCAR { // Bio Chemical Analysis Result
friend class BCAR_MemMgr;
protected:
BCAR() { /* !!! */ }
public:
BCAR( const unsigned char * );
void *operator new( size_t );
void operator delete( void * );
virtual int size() { return 0; }
. . .
private:
struct {
//
} header;
. . .
};

. new.
new C++ rtl, :
inline void *operator new( size_t, BCAR *p ) {
return p;
}
in place
() ().
this .
.
class BCAR_MemMgr {
friend BCAR;

138


public:
BCAR_MemMgr();
void alloc( int );
void free( BCAR *, int );
BCAR *largest();
private:
. . .
};
. :

static BCAR_MemMgr MemoryManager;


. 
, alloc/free
( alloc , 
, largest 
), largest
. , BCAR::new, :
void *BCAR::operator new( size_t ) {
return MemoryManager.largest();
}
? , 
( new BCAR), 
, alloc .
.
:
class Phlegm: public BCAR {
friend BCAR;
private:
int size() { retrurn sizeof( Phlegm ); }
struct PhlegmAnalysisBody {
//
};
PhlegmAnalysisBody body;
Phlegm( const unsigned char *data ): BCAR() {
MemoryManager.alloc( size() );
::memcpy( &body, data + sizeof( header ), sizeof( body ) );
}
. . .
};

139

. :
BCAR::BCAR( const unsigned char *dataStream ) {
::memcpy( &header, dataStream, sizeof( header ) );
if( CRC_OK( dataStream ) ) {
//
//
switch( AnalysisOf( dataStream ) ) {
case PHLEGM:
::new( this ) Phlegm( dataStream );
break;
case BLOOD:
::new( this ) Blood( dataStream );
break;
case ...:
. . .
}
. . .
}
, 
, .
, . 
( malloc, ).
( stream), ,
. :
BCAR *analysis = new BCAR( stream );
BCAR.
BCAR::new, 
MemoryManager.largest(). ,
BCAR
BCAR::BCAR( const unsigned char * ).
( stream) 
new ( )
BCAR . 
, BCAR::BCAR().
, BCAR::BCAR()
.
MemoryManager.alloc( int ),

. ,
MemoryManager :
void BCAR::operator delete( void *p ) {

140

MemoryManager.free( (BCAR *)p, ((BCAR *)p) >size() );


}
, 
.
,
.
Ho .
,
. 
, .
, 
, .
( ) . , 
, , common practice.
common practice 
unsigned char storage[ 1 ] , 

, .
, ,
. 
.  :
class Blood: public BCAR {
friend BCAR;
private:
int bodySize;
int size() { return sizeof( Blood ) + bodySize; }
int getSize( const char * );
sturct BloodAnalysisBody {
//
} *body;
Blood( const unsigned char *data ): BCAR() {
body = (BloodAnalysisBody *) bodyStorage;
bodySize = getSize( data );
::memcpy( bodyStorage, data + sizeof( header ), bodySize );
MemoryManager.alloc( size() );
}
unsigned char bodyStorage[ 1 ];
}
body>,

141

, ,
.
,
.  :
class Blood: public BCAR {
friend BCAR;
private:
int bodySize;
int size() { return sizeof( Blood ) + bodySize; }
int getSize( const unsigned char * );
struct BloodAnalysisBody {
//
} *body;
Blood( const unsigned char *data ): BCAR() {
body = (BloodAnalysisBody *) ((unsigned char *)this
+ sizeof( Blood ));
bodySize = getSize( data );
::memcpy( body, data + sizeof( header ), bodySize );
MemoryManager.alloc( size() );
}
}
, 
MemoryManager ( , , 
, ), alloc 
.

11.

. 
 . , 
Unix, Windows, DOS, ,
( ) 
,
( Unix Unix 

).
 
. , , 

142

, , C++

, 
, ,
.. ..
, 
.
Unix, . , ,
. :
C++, ,
?. , , ,
. 
, , Java, 
. C++ ,
: Hello, world!?
C++ ?.
, .

. .., , 
, DirectX
OpenGL . , 
OpenGL ,

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

, ,
,
.
, , 
.
 , 
? , Explorer
flat buttons Delphi/C++ Builder,

143

Internet Explorer 3.0.  ,


, 
...

144


char name[10];
// ...

.
 , 
, . ,
.

, , , 
, 
, .

puts("Enter you name:");


gets(name);
, 9 , ,
10, (name + 10) 0. 
, (, 
,  ,
), , .

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

.
, , 

,
. ,
,
, ,  
...

12.
gets()

,

gets()  .

gets(), ,
:
char* gets(char* s);
stdio.h.
stdin. s
NULL .
, . 
, , ,
... , gets(),
.
, , , 
gets() , ,
. , gets() , .. 
, , 
, . ,

. .., :

 
. , 
, ;  
, , , 1024
, ,
gets().
, 
.
void foo()
{
char name[10];
// ...
puts("Enter you name:");
gets(name);
// ...
}

145

, name . ,
,
. ,
, name.
, gets() ,
foo().
, ,  
, .
, . 
Unix , 
, ,
. , , , 
. , ps passwd
root'. , 
( ps) ,
/etc/passwd. ,

( 
!). , 
,
 
. ,
(, ),
C++.
: 
.
, ,
. 
, 
. ,
, 
, 
. gets() :
fgets(name, 10, stdin);
gets()
, .
gets() fgets().

146

13.

Delphi ( )
, , 
Borland . 
: Delphi 
.
, C++ Builder, ,
. ,  
,
. 
, class
property , (
). , 
set get, 
.
, 
:
. ,

, .
, ,
. , 
. . , 
... , C++
, (
, ) , 
:
a = b;
, . 
.
( , ) 
,
printf.
.
, . , 
, 
:
class Test

147

{
protected:
int p_a;
int& setA(const int& x);
int getA();
public:
/* ... */ a;
};
// ...
Test t;
t.a = 10; // Test::setA()
int r = t.a; // Test::getA()
. ,
:
template<class A, class T,
T& (A::*setter)(const T&),
T (A::*getter)()
>
class property
{
// ...
};
A ,
(
setter getter). T (, int 
).
,
, , 
C++ , 
 . , 
, ,
,
, ( this). 
, , 
, . 
A::*foo , A
.

148


:
template<class A, class T,
T& (A::*setter)(const T&),
T (A::*getter)()
>
class property
{
protected:
A * ptr;
public:
property(A* p) : ptr(p) { }

const T& operator= (const T& set) const


{
assert(setter != 0);
return (ptr >*setter)(set);
}
operator T() const
{
assert(getter != 0);
return (ptr >*getter)();
}
};
(
,
inline,
,
. , 
 ,
( Java). .
, .
 :
(ptr >*f)();
, , .
,
, . ..,
.
property :
class Test
{
// ...

149

property<Test, int, &Test::setA, &Test::getA> a;


Test() : a(this) { }
};
g++, msvc bcc32 
. , 
, 
, ,
.. , 
.
. 
. , 
. ,

. ,
, 
, .
,
, .
(..,
persistent object). , 
. ?
, 
. , 
, 
. , .

14.


.
. ,
:
i = 10; // 10 i
. , , 
, . 
.
; 
,

150

; . 
, 
.
:
/**********************************************
* function
*/
void function()
{
}
,
,
. , ,
; 
,  .
, .
, . 
, ,
, . 
, , 
, , 
cut&paste,
.

, . ,
, , 
. , , , 

.
, ,
.

,  . ,
, , ,
. 
,  ,
, ,
. :
{
/*
*

151

*/
}
,
.
, , 
. 
, , . 
, ;
, 
. , C++
. , dictionary::Creator
index::Creator:
Creator ( , ,
, Creator 
), ,
.
,
. , 
. : ,
,
. ,
, 
. ,
, ,
.

, , .
, 
, ,
.
,
, 

. 
,
.
, 
.

. 

152

. 
, Java, , JavaDoc, C++ doc++
doxygen. 

.
,
. .

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

( , 
TeX). ,
, Web.
Pascal', . ,
Web Web .
Web ,
. 
.. 
, , ,
, , 
.
Web : 
( )
. , TeX 
Web', Web TeX'...
, ?
Web ,
. 
, Web,
( ). ,
: 
, . 
.

153

, Web' 
( ,
?), 
.

154


doxygen :

html;

LaTeX;

doxygen .

RTF;

/**
* \bref .
*
*
* .
*/
class AutoDoc
{
public:
int foo() const; //!< . .

man.

/**
* \brief .
*
* : . foo()
* .
*
* \param ignored .
*
* \warning .
*
* \note .
*
* \see foo().
*/
int bar(int ignored);
};
doxygen .
/**, /*! //!<. doxygen
. 

( ). 

(
),
.

, , (
) MS HTML Help (
MSDN), PDF ( LaTeX).
,
.
( ), 
, pcGRASP, 
. : 
. pcGRASP  :
( 
), ( ),
( , 
, return) .. , ,
. , indent () pcGRASP ( 
, ), 
.
, ,
, . 
, ,
.

, , , 
, . ,

doxygen.

15.
C

, , perl,
PHP, JavaScript. 

155

156

, ,
Perl ,
.

. ,
, ,
.

, , 
CGI ,
.

, . ,

, .
,

, 
, .

,  
. HTML 
, 
. 
, .
, , TCP/IP. 
,
, CGI 
? , CGI 
.
 
. .., Apache, Internet Explorer lynx
.
, 
CGI , , 
, ,
  ( 
, ). ... ,
. ,
.
, ,
, .
 CGI,
? ,
PHP? . 
. 
, , , ,
.
TCP,
, , 
(BSD sockets) 

.

. 
,
(, , ), 

,
,
,  . 

, ,
. ,

.
, 
.
, , , 
, .
,
. 

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

.
, ,
.

157

, 
,
. , , CGI
, ,

.

158

select()
,
.
, ,
libwww, 
.

,
, ;  
, 
. : libwww, 
, . ,
. , 
HTML, HText, 
.
this C++, .. .
HText , callback
. , 
( , .. 
, ),
, , , ,

.


.
( fetch), libwww 
, ,
. , 
, , , text/html
text/present ( libwww, present ,
). 
html ( sgml html dtd).

.
. , ,
, , 
, , , 
, libwww.
, .
, HText libwww
Examples, , 
.

, , 
libwww, , 
. , 
.

. 
, ,
libwww, , 
.

libwww, 
lynx, .

, libwww
web, , , 
 . , 
libwww 
.

 ( 
!) C++ libwww. 
.

, libwww,
.
.
libwww
. , 
, 
,
, .

16.


( , ,

159

),
. ... , 
: . , .
C++
, .
, ,
. , ;
,  
, 
, 
: segmentation fault.
, core dumped,
: , , 
, , . , ,
, ?
? .
Java , 
. 

.
, , ,
.
, 
. ,   ,
core dumped, , , 
. ,
:
(
, ).
, ,
. , , .
: 
,  . 
, ,
, , ,
. 
: , , ? ,
, ?

160

. , 

, , ,
:
char buf[100];
? 100? 
.
, . 
, .
, ..

.  ?
. 
,  . , ,
... ? 
. 
, 
...
,
 , .
,
... , 
,  
... .
, , , 
, 
. ?

,
. , ,
( 
, #if 0 ... #endif) , 
, , .
,
, , ,

... ?
, 
. , 

161

 .
, ,


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

, .
DEBUG/RELEASE ,

(, , Java: 
, ).
( ;
)).
, C++
. , , 
,
. inline,
.
,
. , Buffer 
.
, , 
, C++ 
. 
, .
C++ .

17.
ploticus
,
, ploticus.


162

, 
.
, , ploticus
: . , ,
, 
... .
. 
ploticus, 
.
. Ploticus, , 
, , 
(, ).
. , ploticus
(, ?) ,
.
.
, ploticus 
, .
. :
() , 
.
, 
, (!) (!!), 
. , , 
, ,

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

, .
, 
,
, ,
.
. ,
, .

163

( ):
/*
* ...
*/
else if( stricmp( attr, "data" )==0 ) {
FILE *tfp;
sprintf( datafile, "%s_D", Tmpname );
getmultiline( "data", lineval, fp, MAXBIGBUF, Bigbuf );
tfp = fopen( datafile, "w" );
if( tfp == NULL ) return( Eerr( 294, "Cannot open tmp data
file", datafile ));
fprintf( tfp, "%s", Bigbuf );
fclose( tfp );
}
/*
* ...
*/

. , fprintf "%s" 
, , 80 
:
/*
* ...
*/
if( standardinput || strcmp( datafile, " " ) ==0 ) { /* a file of
" " means read from stdin */
dfp = stdin;
goto PT1;
}
if( strlen( datafile ) > 0 ) sprintf( command, "cat %s", datafile
);
if( strlen( command ) > 0 ) {
dfp = popen( command, "r" );
if( dfp == NULL ) {
Skipout = 1;
return( Eerr( 401, "Cannot open", command ) );
}
PT1:
/*
* ...
*/

164

if( strlen( datafile ) > 0 ) sprintf( command, "cat %s", datafile


);
:
dfp = popen( command, "r" );
, . ... , 
fopen()
( ), :
dfp = stdin;
goto PT1;
, .  , , 
, : data 
, datafile. , 
, , ,
, stdin. , 
, datafile. ,
, ,
, cat datafile. 
, command, 
. ,
(pipe) popen(), 
FILE (
).
?

18.


,  .
,
API 
, . 
XML.


.
, 
. 
,

165

, 

. ,
MSDN, , , 
.


(Automation)
( Word Excel) 
, .
, 
, ,
.
,
. 
,

.

.
COM.
,

. . , 
IUnknown, COM.

.
IDispatch, 
IUnknown. IDispatch
.
,
. , ,
IDispatch,
, , 
ClassWizard Visual C++.

dispatch , 
,
ProgId.

166

, progid Excel Excel.Application.


VBScript
CreateObject, ProgID.
.

MFC
MFC ,
CmdTarget. CmdTarget, 
dispatch
. ClassWizard
(View ClassWizard Add Class New), CmdTarget,
Automation Creatable by ID, 
ProgID. 
, , ,
. , 
, .
COM .
, 
, ,
. ,
.
(reference count). 
, , 
. 
, .
ProgID , CTestApp (
, AutomationServer) , 
CTestAutomatedClass .
ProgID COM,
Proxy. 
, ,
, . ,
COM,
.
CCmdTarget GetIDispatch(),
IDispatch.
, .

COM
COM ,
MFC. 

167

? ! OLE COM
, .
MFC COM
.
, , 
Windows,
COM?
, , COM,
, COM 
. , ,
, COM.
, 
COM, .
, Controller.
class Controller
{
public:
Controller (HWND hwnd, CREATESTRUCT * pCreate);
~Controller ();
// ...
private:
UseCom _comUser; // I'm a COM user
Model _model;
View _view;
HINSTANCE _hInst;
};
, COM 
,
, 
( , , ).
UseCom .
class UseCom
{
public:
UseCom ()
{
HRESULT err = CoInitialize (0);
if (err != S_OK)
throw "Couldn't initialize COM";
}

168

~UseCom ()
{
CoUninitialize ();
}
};
, ? ,
COM 
. , , 
, .
. , 
, ,
.. : , !
. 
COM 
. , .
template <class T>class SIfacePtr
{
public:
~SIfacePtr ()
{
Free ();
}
T * operator >() { return _p; }
T const * operator >() const { return _p; }
operator T const * () const { return _p; }
T const & GetAccess () const { return *_p; }
protected:
SIfacePtr () : _p (0) {}
void Free ()
{
if (_p != 0)
_p >Release ();
_p = 0;
}
T * _p;
private:
SIfacePtr (SIfacePtr const & p) {}
void operator = (SIfacePtr const & p) {}
};
, (
).

169

. . , 
: , 
. 

. , 
SIfacePtr, ,
, .
=
, , 
,
. . 
, 
COM. , .
, ,
. ,
, 
.
API , 
. 
, , 

. , , 
, 
.
template <class T>
class SShellPtr
{
public:
~SShellPtr ()
{
Free ();
_malloc >Release ();
}
T * weak operator >() { return _p; }
T const * operator >() const { return _p; }
operator T const * () const { return _p; }
T const & GetAccess () const { return *_p; }
protected:
SShellPtr () : _p (0)
{
// Obtain malloc here, rather than

170

// in the destructor.
// Destructor must be fail proof.
// Revisit: Would static IMalloc * _shellMalloc work?
if (SHGetMalloc (& _malloc) == E_FAIL)
throw Exception "Couldn't obtain Shell Malloc";
}
void Free ()
{
if (_p != 0)
_malloc >Free (_p);
_p = 0;
}
T * _p;
IMalloc * _malloc;
private:
SShellPtr (SShellPtr const & p) {}
void operator = (SShellPtr const & p) {}
};
: SShellPtr 
.
.
, , _shellMalloc
SShellPtr. , 
WinMain. 
COM . , 
, API
CoGetMalloc CoInitialize.
, SHGetMalloc, ,
.
, ,
.
, 
, COM,
, CoGetMalloc.
_malloc
( SComMalloc:: GetMalloc 
):
IMalloc * SComMalloc::_malloc = SComMalloc::GetMalloc ();
IMalloc * SComMalloc::GetMalloc ()
{
IMalloc * malloc = 0;
if (CoGetMalloc (1, & malloc) == S_OK)

171

return malloc;
else
return 0;
}
, ,
Windows COM . .
Windows , 
. , Windows 
, ,
? , , 
, 
, , .. , ,
(PMDFS poor man's Distributed File
System). PMDFS? 
. ,
, PMDFS. ,
, , 
, 
.
char path [MAX_PATH];
path [0] = '\0';
Desktop desktop;
ShPath browseRoot (desktop, unicodePath);
if (browseRoot.IsOK ())
{
FolderBrowser browser (hwnd,
browseRoot,
BIF_RETURNONLYFSDIRS,
"Select folder of your choice");
if (folder.IsOK ())
{
strcpy (path, browser.GetPath ());
}
}
, desktop.
IShellFolder. ,
. ,
API SHGetDesktopFolder. 
( ).
class Desktop: public SIfacePtr<IShellFolder>
{
public:

172

Desktop ()
{
if (SHGetDesktopFolder (& _p) != NOERROR)
throw "SHGetDesktopFolder failed";
}
};
, 
, PMDFS. ShPath 
. Unicode (
mbstowcs, ASCII Unicode: int
mbstowcs(wchar_t *wchar, const char *mbchar, size_t count)). 
. 
,
SShellPtr,
.
class ShPath: public SShellPtr<ITEMIDLIST>
{
public:
ShPath (SIfacePtr<IShellFolder> & folder, wchar_t * path)
{
ULONG lenParsed = 0;
_hresult =
folder >ParseDisplayName (0, 0, path, & lenParsed, & _p, 0);
}
bool IsOK () const { return SUCCEEDED (_hresult); }
private:
HRESULT _hresult;
};
,
.
, , 
.
SShellPtr<ITEMIDLIST>.
, ITEMIDLIST 
.
class FolderBrowser: public SShellPtr<ITEMIDLIST>
{
public:
FolderBrowser (
HWND hwndOwner,
SShellPtr<ITEMIDLIST> & root,

173

UINT browseForWhat,
char const *title);
char const * GetDisplayName () { return _displayName; }
char const * GetPath () { return _fullPath; }
bool IsOK() const { return _p != 0; };
private:
char _displayName [MAX_PATH];
char _fullPath [MAX_PATH];
BROWSEINFO _browseInfo;
};
FolderBrowser::FolderBrowser (
HWND hwndOwner,
SShellPtr<ITEMIDLIST> & root,
UINT browseForWhat,
char const *title)
{
_displayName [0] = '\0';
_fullPath [0] = '\0';
_browseInfo.hwndOwner = hwndOwner;
_browseInfo.pidlRoot = root;
_browseInfo.pszDisplayName = _displayName;
_browseInfo.lpszTitle = title;
_browseInfo.ulFlags = browseForWhat;
_browseInfo.lpfn = 0;
_browseInfo.lParam = 0;
_browseInfo.iImage = 0;
// Let the user do the browsing
_p = SHBrowseForFolder (& _browseInfo);
if (_p != 0)
SHGetPathFromIDList (_p, _fullPath);
}
! ?

, ,

, ,
.
,
, ,

174

.
.
, , .
,
C f, C,
:
if (f )
f C;
else if (f operator>> operator<<)
{
f ;
if (f C)
f C;
}
else if ( f
)
{
f ;
if (f C)
f C;
}
else
f C;
,
, ,
C. ,
f  ()
, , 
? , , .
:
if (f )
f C;
else if (f operator>> operator<<)
{
f ;
if (f C)
f C;
}
else if (f
)
{
f ;

175

if (f C)
f C;
}
else if (f
)
f ;
else
f C;
. ,
. ,
, .
,
. , 
:
struct Point {
int x, y;
};
, 
.
, .
. , 
x y , , 
. 
, x y .
: 
. 
, , , .

. ,
, , 
. , Point. , 
, 
.
,
, ,
, :
class Point {
public:
int getXValue() const;
int getYValue() const;
void setXValue(int newXValue);
void setYValue(int newYValue);

176

private:
... // ...
};
, 
( x y ), 
, , , 
. ,
.
, 
.
, ,
.
,
, , , 
.


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

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

177

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



, , 
. , n 
, n+1 .
, ,
: f
, , 
, 
.
( f 
, f ), 
.
, 
, . , 
,  
. ,
 
. , ,  
. 
, ,
.
, 
. , 

178

, 
.
, , 
, , .
, (Widgets) 
,
, ,
:
// a design less encapsulated than it could be
class Widget {
... // Widget; :
// public, private, protected
public:
//
static Widget* make(/* params */);
};
Widget, 
. , Widget 
(make)  , 
(namespace):
//
namespace WidgetStuff {
class Widget { ... };
Widget* make( /* params */ );
};
, , 
.


, , 
, 
. , 
. , ,
Wombat
. , ,
, ,
. 
, , :
class Wombat {
public:
void eat(double tonsToEat);

179

180

...
};
void sleep(Wombat& w, double hoursToSnooze);

,

nap(w);
, , 
, . 
(wombats), ,
, .

Wombat w;
:

, ,

, ,
,  . 
, , 
, .
C++ , . 
,
. , 
, , 
. . STL
( C++), 
(, size), (, unique),
(, find). .

w.eat(.564);
eat. :
sleep(w, 2.57);
sleep.
:
class Wombat {
public:
void eat(double tonsToEat);
void sleep(double hoursToSnooze);
...
};
w.eat(.564);
w.sleep(2.57);
, ! 
, ,
.
,
. Wombat. ,
, 
, , 
, . , 
w.sleep (.5), (.5)
, . , 
? 
, 
, ,
. , Wombat,
, :
// inline,
void nap(Wombat& w) { w.sleep(.5); }
Wombat w;
...


(, 
, ) , 
. ,
C++ . 
, , ,
! 
,
, 
. , , 
.
, Wombat ,
Wombat , ,
, .
.
( ) . 
,
.
, , 
,
. , , 

181

, 
.
.
Wombat 
, 
Wombat : 
Wombat ( , ),
, , ,
. 
, .
, 
, . , 
,
(STL). namespace std 50 
. ,
, , .
, . 
, , 
, ,
,
, , 
. , 
, , 
. , . ,
.


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

182

, 
. 
, 
,
.
, ,
, ,
.

,
.
,
, 
, , 
, 
( ).
, ,
, 
, 
, 
,
.
, ,
, . 
? ,
,
.
,
 ,
, 
. ,
,
, .
, 
. : Java ? 
?
,
!? 
. 
!?

183

19.
C/C++ EMX Watcom
Watcom C/C++
Watcom . 
. DOS
real mode, DOS protected mode (DOS/4G, DOS/4GW, Phar Lap), Win16,
Win32, Win32s, QNX, OS/2 (16 32bit), Netware NLM. ,
,
( , Win32 
 OS/2 ..). Watcom
DOS, (DOOM ).
11.0 (1997 .) , 
Watcom, Sybase Inc., , ,
. 
, 1999 . Sybase Inc. 
, 
, (
2000 .). .
11.0B. C++ 
namespaces STL. , 
STL, Watcom C++ ( , STLPort).

: , , (), make, lib, strip . 
GUI (OS/2, Windows) IDE ( ).
1997 ., MS Visual
C++ Watcom (,
Windows, ).
Watcom C++ OS/2 :

11.0* ,
16 OS/2 (Vio*, Kbd*, Mou* .)
.
LXFix,
fixups.
OS/2 Toolkit ( OS/2
2.x). Toolkit
(4.0, 4.5).

184

OS/2, Watcom C/C++


, .
_dos_setdrive(), 
(, OS/2,
Win32 DOS)
( 
Turbo Vision).
,
. 
.

EMX (GNU C/C++)


EMX Unix OS/2
Unix DOS. , 
. 
Unix OS/2,
, fork().

GCC (gcc GNU Compiler Collection). GCC
( 
C, C++, Objective C, Fortran 77, Chill Java, 
),
( RTL
Register Transfer Language) RTL
. ,
i386.
EMX GCC OS/2/DOS 
, , gdb
; C,
Unix; DLL . ,
EMX OS/2 Unix,
GNU Make, 
.
, EMX 
OS/2, OS/2 API.
, .
, OS/2 API
Unix,  DOS flat mode (
EMX DOS). ,
Windows rsx.exe,
a.out, EMX!

185

GCC Unix, EMX 


 . :

('/'). , Unix

. ,
(open(), fopen() .) ,

. ( , c:/aaa/bbb/ccc
.)
. ,
.o a.out,
.obj.
(.a .lib).

a.out, LX
.

. .obj ,
LX .exe (
link386). ( 
DLL) 
. , .obj
LX .exe, DOS 
. , 
. ,
(
a.out EMX
runtime).

C, C++. ,
,
.

. ..

.
, . ,
:


pipes (
, )
.

186

. 

, ,
.

EMX 
. , EMX, 
sock_init(), read() write(),
soclose() close(). , select(), 
IBM TCP/IP , EMX 
, Unix'e.
, GCC
GNU. GCC,  80 . 
90 ., ,
GNU . (rms); 1996 . 
2.7.2.1 2.8.1. 
C ANSI C + ,
C++ ; , .
2.8.1 GCC Cygnus, 
C++ ( 
C++ ). 
EGCS (Enhanced GNU Compiler Suite),
. 
2.8.1, C++,
, EGCS 
GCC (2.95), GCC
Cygnus.
2.95.2, 27 1999 . ( Cygnus 
Red Hat Inc.)
GCC , 
C++ ( namespace) 
STL SGI ( libstdc++,
2.90.8). STL libstdc++ , iostreams
templatebased, libg++. ,
STLport, GCC.
GCC . , 
GCC OS/2 EMX, 
(v0.9d) GCC 2.8.1. .
PGCC, Pentiumoptimized GCC.

187

GCC 
, (
Pentium Cyrix, AMD,
, )
. PGCC GCC
, . (PGCC
GCC). PGCC 2.95.3, GCC 2.95.2.

, ,
GCC 2.95.2, .
OS/2. 
2.95.2 . 
( EGCS 1.1.2
), , .
O6 Pentium
( PGCC). PM
. PMGDB, 
EMX, , . 
profiling ( , , reset).
. ,
.
GCC (C C++), ,
Unix OS/2. ,
, ,
. , EMX , 
Unix. , ,
EMX. , 
, , shared memory ( BSD, POSIX).
, GCC win32, DOS (
a.out, EMX,
DOS win32!), EMX
, OS/2, Unix,
DOS Windows.
EMX 
. , , 
: , XFree86,
EMX OS/2! 
.

188

20.
#import
VC
?

Excel Word ( .. Word
) VBA.
. (
) . ?
OLE?

Fidonet, Visual C++. ,
,
, #import.
,
. ,
.
#import Visual C++, 5.0.

COM, .

,
COM . , ,
OLE . , Visual Basic, 
, .
, OLE
VB ,
VB.
C++ (
?), , , 
(wrappers) IDispatch.
VC .
COleDispatchDriver,
MFC. MFC ClassWizard', 
Add Class From a type
library. , 
, , 

189

. 
, ClassWizard ,
, ,
Put Get 
.
CComDispatchDriver ATL.
VC , ,

ID, , 
.

190


dual,
helpstring("ISamplObject Interface"),
pointer_default(unique)
]
interface ISamplObject : IDispatch
{
[propget, id(1)] HRESULT Prop([out, retval] SamplType *pVal);
[propput, id(1)] HRESULT Prop([in] SamplType newVal);
[id(2)] HRESULT Method([in] VARIANT Var,[in] BSTR Str,[out,
retval] ISamplObject** Obj);
};

#import.
OLE Automation
,
.
.
IDL, . 
SamplType
ISamplObject, 
Prop Method.
import "oaidl.idl";
import "ocidl.idl";
[
uuid(37A3AD11 F9CC 11D3 8D3C 0000E8D9FD76),
version(1.0),
helpstring("Sampl 1.0 Type Library")
]
library SAMPLLib
{
importlib("stdole32.tlb");
importlib("stdole2.tlb");
typedef enum {
SamplType1 = 1,
SamplType2 = 2
} SamplType;
[
object,
uuid(37A3AD1D F9CC 11D3 8D3C 0000E8D9FD76),

[
uuid(37A3AD1E F9CC 11D3 8D3C 0000E8D9FD76),
helpstring("SamplObject Class")
]
coclass SamplObject
{
[default] interface ISamplObject;
};
};

#import ,
. sampl.tlh,
, sampl.tli, .
.
.
#pragma once
#pragma pack(push, 8)
#include <comdef.h>
namespace SAMPLLib {
// Forward references and typedefs struct __declspec
(uuid("37a3ad1d f9cc 11d3 8d3c 0000e8d9fd76"))
/* dual interface */ ISamplObject;
struct /* coclass */ SamplObject;
// Smart pointer typedef declarations _COM_SMARTPTR_TYPEDEF
(ISamplObject, __uuidof(ISamplObject));
// Type library items

191

enum SamplType
{
SamplType1 = 1,
SamplType2 = 2
};
struct __declspec(uuid("37a3ad1d f9cc 11d3 8d3c 0000e8d9fd76"))
ISamplObject : IDispatch
{
// Property data
__declspec(property(get=GetProp,put=PutProp)) enum SamplType
Prop;
// Wrapper methods for error handling
enum SamplType GetProp ( );
void PutProp (enum SamplType pVal );
ISamplObjectPtr Method (const _variant_t & Var,_bstr_t Str );
// Raw methods provided by interface
virtual HRESULT __stdcall get_Prop (enum SamplType * pVal) = 0 ;
virtual HRESULT __stdcall put_Prop (enum SamplType pVal) = 0 ;
virtual HRESULT __stdcall raw_Method (VARIANT Var,BSTR
Str,struct ISamplObject** Obj) = 0 ;
};
struct __declspec(uuid("37a3ad1e f9cc 11d3 8d3c 0000e8d9fd76"))
SamplObject;
#include "debug\sampl.tli"
} // namespace SAMPLLib

192

inline void ISamplObject::PutProp ( enum SamplType pVal ) {


HRESULT _hr = put_Prop(pVal);
if (FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this));
}
inline ISamplObjectPtr ISamplObject::Method ( const _variant_t &
Var, _bstr_t Str ) {
struct ISamplObject * _result;
HRESULT _hr = raw_Method(Var, Str, &_result);
if (FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this));
return ISamplObjectPtr(_result, false);
}

sampl.tlh:
namespace SAMPLLib {
, 
, .

, , ,
IDocument. ,
:
#import "sampl.dll" rename_namespace("NewNameSAMPLLib")
#import "sampl.dll" no_namespace
Method:
ISamplObjectPtr Method (const _variant_t & Var,_bstr_t Str);

COM. .

_com_error.
,

(, _variant_t
,
).

_com_ptr_t.
COM
.

#pragma pack(pop)

#pragma once
// interface ISamplObject wrapper method implementations
inline enum SamplType ISamplObject::GetProp ( ) {
enum SamplType _result;
HRESULT _hr = get_Prop(&_result);
if (FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this));
return _result;

193

_variant_t. VARIANT
,
VARIANT
.

_bstr_t. BSTR.

,
.

ISamplObjectPtr.
_com_ptr_t. smart
COM.
, . #import 
smart.
.
// Smart pointer typedef declarations
_COM_SMARTPTR_TYPEDEF(ISamplObject,__uuidof(ISamplObject));
:
typedef _com_ptr_t<ISamplObject,&__uuidof(ISamplObject)>
ISamplObjectPtr
smart
COM, .. AddRef Release
IUnknown 
_com_ptr_t.
,
:
Interface* operator >() const throw(_com_error);
Interface , ISamplObject. 
,
COM . 
#import :
#import "sampl.dll"
void SamplFunc ()
{
SAMPLLib::ISamplObjectPtr obj;
obj.CreateInstance(L"SAMPLLib.SamplObject");
SAMPLLib::ISamplObjectPtr obj2 = obj >Method(1l,L"12345");
obj >Prop = SAMPLLib::SamplType2;
obj2 >Prop = obj >Prop;
}

194

COM
, #import, . 
, smart 
.
CreateInstance _com_ptr_t, :
SAMPLLib::ISamplObjectPtr obj;
obj.CreateInstance(L"SAMPLLib.SamplObject");

obj.CreateInstance(__uuidof(SamplObject));
,
:
SAMPLLib::ISamplObjectPtr obj(L"SAMPLLib.SamplObject");

SAMPLLib::ISamplObjectPtr obj(__uuidof(SamplObject));
, 
. ,
#import
_com_error. HRE
SULT, IErrorInfo 
. 
:
#import "sampl.dll"
void SamplFunc ()
{
try {
using namespace SAMPLLib;
ISamplObjectPtr obj(L"SAMPLLib.SamplObject");
ISamplObjectPtr obj2 = obj >Metod(1l,L"12345");
obj >Prop = SAMPLLib::SamplType2;
obj2 >Prop = obj >Prop;
} catch (_com_error& er) {
printf("_com_error:\n"
"Error : %08lX\n"
"ErrorMessage: %s\n"
"Description : %s\n"
"Source : %s\n",
er.Error(),
(LPCTSTR)_bstr_t(er.ErrorMessage()),
(LPCTSTR)_bstr_t(er.Description()),
(LPCTSTR)_bstr_t(er.Source()));

195

}
}
sampl.tli #import
. 
:
if (FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this));
, , , 
. , MoveNext
Recordset ADO , ,
. , 
. 
try {} catch, wrapper, 
.
, , *.tlh 
, #include. .
,
. MS Word, MS Excel, ADO
DB ActiveX Control. 
, ,
COleDispatchDriver MFC Class Wizard'
#import.

:
// Office.h
#define Uses_MSO2000
#ifdef Uses_MSO2000
// for MS Office 2000
#import "C:\Program Files\Microsoft Office\Office\MSO9.DLL"
#import "C:\Program Files\Common Files\Microsoft
Shared\VBA\VBA6\VBE6EXT.OLB"
#import "C:\Program Files\Microsoft Office\Office\MSWORD9.OLB" \
rename("ExitWindows","_ExitWindows")
#import "C:\Program Files\Microsoft Office\Office\EXCEL9.OLB" \
rename("DialogBox","_DialogBox") \
rename("RGB","_RGB") \
exclude("IFont","IPicture")
#import "C:\Program Files\Common Files\Microsoft
Shared\DAO\DAO360.DLL" \
rename("EOF","EndOfFile") rename("BOF","BegOfFile")
#import "C:\Program Files\Microsoft Office\Office\MSACC9.OLB"
#else

196

// for MS Office 97
#import "C:\Program Files\Microsoft Office\Office\MSO97.DLL"
#import "C:\Program Files\Common Files\Microsoft Shared\VBA\VBE
EXT1.OLB"
#import "C:\Program Files\Microsoft Office\Office\MSWORD8.OLB" \
rename("ExitWindows","_ExitWindows")
#import "C:\Program Files\Microsoft Office\Office\EXCEL8.OLB" \
rename("DialogBox","_DialogBox") \
rename("RGB","_RGB") \
exclude("IFont","IPicture")
#import "C:\Program Files\Common Files\Microsoft
Shared\DAO\DAO350.DLL" \
rename("EOF","EndOfFile")
rename("BOF","BegOfFile")
#import "C:\Program Files\Microsoft Office\Office\MSACC8.OLB"
#endif
MS Word, MS
Excel MS Access. MS
Office 2000, MS Office 97, 
:
#define Uses_MSO2000
MS Office , C:\Program
Files\Microsoft Office\Office\, 
. rename,
, 
. , ExitWindows 
winuser.h :
#define ExitWindows(dwReserved,Code)
ExitWindowsEx(EWX_LOGOFF,0xFFFFFFFF)
, , ExitWindows,
.
rename, .

MS Word
// console.cpp : Defines the entry point for the console
application.
#include "stdafx.h"
#include <stdio.h>
#include "Office.h"
void main()

197

198

::CoUninitialize();
::CoInitialize(NULL);
try {
using namespace Word;
_ApplicationPtr word(L"Word.Application");
word >Visible = true;
word >Activate();
//
_DocumentPtr wdoc1 = word >Documents >Add();
//
RangePtr range = wdoc1 >Content;
range >LanguageID = wdRussian;
range >InsertAfter(" ");

// HTML
wdoc1 >SaveAs(&_variant_t("C:\\MyDoc\\test.htm"),
&_variant_t(long(wdFormatHTML)));
// ,
// .. char* VARIANT*
// test.doc
_DocumentPtr wdoc2 = word >Documents >Open
(&_variant_t("C:\\MyDoc\\test.doc"));
//
word >Run("Macro1");
} catch (_com_error& er) {
char buf[1024];
sprintf(buf,"_com_error:\n"
"Error : %08lX\n"
"ErrorMessage: %s\n"
"Description : %s\n"
"Source : %s\n",
er.Error(),
(LPCTSTR)_bstr_t(er.ErrorMessage()),
(LPCTSTR)_bstr_t(er.Description()),
(LPCTSTR)_bstr_t(er.Source()));
CharToOem(buf,buf); //
printf(buf);
}

MS Excel
// console.cpp : Defines the entry point for the console applica
tion.
#include "stdafx.h"
#include <stdio.h>
#include "Office.h"
void main()
{
::CoInitialize(NULL);
try {
using namespace Excel;
_ApplicationPtr excel("Excel.Application");
excel >Visible[0] = true;
//
_WorkbookPtr book = excel >Workbooks >Add();
// ( VBA )
_WorksheetPtr sheet = book >Worksheets >Item[1L];
// VBA :
// book.Worksheets[1]
// Item
// (id[0]), VB
// . C++ , , .
//
sheet >Range["B2"] >FormulaR1C1 = " 1";
sheet >Range["C2"] >FormulaR1C1 = 12345L;
sheet >Range["B3"] >FormulaR1C1 = " 2";
sheet >Range["C3"] >FormulaR1C1 = 54321L;
//
sheet >Range["B4"] >FormulaR1C1 = ":";
sheet >Range["C4"] >FormulaR1C1 = "=SUM(R[ 2]C:R[ 1]C)";
sheet >Range["C4"] >Activate();
//
sheet >Range["A4:D4"] >Font >ColorIndex = 27L;
sheet >Range["A4:D4"] >Interior >ColorIndex = 5L;
// L , //
long.

199

// long short //
_variant_t, .. // int
_variant_t . //
, //
int.
} catch (_com_error& er) {
char buf[1024];
sprintf(buf,"_com_error:\n"
"Error : %08lX\n"
"ErrorMessage: %s\n"
"Description : %s\n"
"Source : %s\n",
er.Error(),
(LPCTSTR)_bstr_t(er.ErrorMessage()),
(LPCTSTR)_bstr_t(er.Description()),
(LPCTSTR)_bstr_t(er.Source()));

CharToOem(buf,buf); //
printf(buf);
}
::CoUninitialize();
}

ADO DB
// console.cpp : Defines the entry point for the console applica
tion.
#include "stdafx.h"
#include <stdio.h>
#import "C:\Program Files\Common Files\System\ado\msado20.tlb" \
rename("EOF","ADOEOF") rename("BOF","ADOBOF")
// rename , .. EOF
// stdio.h
using namespace ADODB;
void main()
{
::CoInitialize(NULL);
try {
//
_ConnectionPtr con("ADODB.Connection");

200


con >Open(L"Provider=Microsoft.Jet.OLEDB.3.51;"
L"Data Source=Elections.mdb","","",0);
//
_RecordsetPtr rset("ADODB.Recordset");
rset >Open(L"ElectTbl",(IDispatch*)con,
adOpenDynamic,adLockOptimistic,adCmdTable);
FieldsPtr flds = rset >Fields;
//
rset >AddNew();
flds >Item[L""] >Value = L"";
flds >Item[L""] >Value = L"";
flds >Item[L""] >Value = L"";
flds >Item[L" "] >Value = false;
flds >Item[L" "] >Value = L" ";
rset >Update();
//
flds >Item[L" "] >Value = true;
flds >Item[L" "] >Value = L" ";
rset >Update();
//
rset >MoveFirst();
while (!rset >ADOEOF) {
char buf[1024];
sprintf(buf,"%s %s %s: %s %s\n",
(LPCTSTR)_bstr_t(flds >Item[L""] >Value),
(LPCTSTR)_bstr_t(flds >Item[L""] >Value),
(LPCTSTR)_bstr_t(flds >Item[L""] >Value),
(bool)flds >Item[L" "] >Value? "": "",
(LPCTSTR)_bstr_t(flds >Item[L" "] >Value));
CharToOem(buf,buf);
printf(buf);
rset >MoveNext();
}
} catch (_com_error& er) {
char buf[1024];
sprintf(buf,"_com_error:\n"
"Error : %08lX\n"
"ErrorMessage: %s\n"

201

202

"Description : %s\n"
"Source : %s\n",
er.Error(),
(LPCTSTR)_bstr_t(er.ErrorMessage()),
(LPCTSTR)_bstr_t(er.Description()),
(LPCTSTR)_bstr_t(er.Source()));

DECLARE_DYNCREATE(CMSFlexGrid)
public:

CharToOem(buf,buf); //
printf(buf);
}
::CoUninitialize();

//{{AFX_INSERT_LOCATION}}

AciveX Control
.
ActiveX Control' Components
and Controls Gallery: Menu Project Add To Project Components and
ControlsRegistered ActiveX Controls.
Microsoft FlexGrid
Control. Insert , 
Confirm Classes
CMSFlexGrid OK.
msflexgrid.h msflexgrid.cpp,
. 
:
msflexgrid.h
// msflexgrid.h
#ifndef __MSFLEXGRID_H__
#define __MSFLEXGRID_H__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

MSFlexGridLib::IMSFlexGridPtr I; //
void PreSubclassWindow (); // I
};

#endif
msflexgrid.cpp
// msflexgrid.cpp
#include "stdafx.h"
#include "msflexgrid.h"
IMPLEMENT_DYNCREATE(CMSFlexGrid, CWnd)
void CMSFlexGrid::PreSubclassWindow ()
{
CWnd::PreSubclassWindow();
MSFlexGridLib::IMSFlexGrid *pInterface = NULL;
if (SUCCEEDED(GetControlUnknown() >QueryInterface(I.GetIID(),
(void**)&pInterface))) {
ASSERT(pInterface != NULL);
I.Attach(pInterface);
}
}
, CAboutDlg.
CMSFlexGrid
OnInitDialog, .
FlexGrid :
BOOL CAboutDlg::OnInitDialog()
{
CDialog::OnInitDialog();

#pragma warning(disable:4146)
#import <MSFLXGRD.OCX>
class CMSFlexGrid : public CWnd
{
protected:

m_grid.I >AddItem("12345");
m_grid.I >AddItem("54321");
return TRUE;
}

203

, .
*.tlh. 
, , 
(, , OLE/COM Object Viewer).
. ,
:
book >Worksheets >Item[1L] >Range["B2"] >FormulaR1C1 = " 1";
book >Worksheets >Item[1L] >Range["C2"] >FormulaR1C1 = 12345L;

, DCOM
. :
_WorksheetPtr sheet = book >Worksheets >Item[1L];
sheet >Range["B2"] >FormulaR1C1 = " 1";
sheet >Range["C2"] >FormulaR1C1 = 12345;
MS Office
VBA .
. ,
MS Word 2000 Run. ,
RunOld. MS Word 2000
Run, MS Word 97 
ID MS Word 97 . RunOld
,
MS Word.
. , 
#import. , COleDispatchDriver
MSADODC.OCX , 
#import, ConnectionString 
. , #import ,
dual , COleDispatchDriver
ConnectionString IDispatch::Invoke. , ,
MSADODC.OCX. 
:
inline _bstr_t IAdodc::GetConnectionString () {
BSTR _result;
HRESULT _hr = _com_dispatch_propget(this,0x01,VT_BSTR,&_result);
// HRESULT _hr = get_ConnectionString(&_result);
if (FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this));
return _bstr_t(_result, false);
}

204

MS Office,
12 Mb .
, , . 
PIII, 
. 
, . ,

, #import. 
, , 
12 Mb? #import
#include.
.

21.
Windows
Borland C++ Builder
, .
: ,


.
,
. WIN API.


(hook) ,

.
(Hook
Procedure). 
.
, 
, . 
DLL. ,
:

DLL c ( :
, ).

, .

DLL.

205

++ Builder DLL. 
, .
File New: DLL Wizard
O. Source Type
C++.
. 
.


(DllEntryPoint)
, 
.
#define UP 1//
#define DOWN 2
#define RESET 3
int iAltKey; //
int iCtrlKey;
int iShiftKey;
int KEYBLAY;//
bool bSCRSAVEACTIVE;// ScreenSaver
MOUSEHOOKSTRUCT* psMouseHook;//
DllEntryPoint , 
:
if(reason==DLL_PROCESS_ATTACH)// . .
{
HKEY pOpenKey;
char* cResult=""; // .
long lSize=2;
KEYBLAY=3;
if(RegOpenKey(HKEY_USERS,".Default\\keyboard layout\\toggle",
&pOpenKey)==ERROR_SUCCESS)
{
RegQueryValue(pOpenKey,"",cResult,&lSize);

206


if(strcmp(cResult,"1")==0)
KEYBLAY=1; // Alt+Shift
if(strcmp(cResult,"2")==0)
KEYBLAY=2; // Ctrl+Shift

RegCloseKey(pOpenKey);
}
else
MessageBox(0," "
" ",
"!",MB_ICONERROR);
//
if(!SystemParametersInfo(SPI_GETSCREENSAVEACTIVE,0,&bSCRSAVEACTIVE
,0))
MessageBox(0," "
" ", "!",MB_ICONERROR);
}
return 1;

.
,

(reason==DLL_PROCESS_ATTACH).


:
LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM
lParam),
:

HookProc ;

nCode ,
;

wParam, lParam
.


Alt, Ctrl Shift ( ). 
wParam lParam. 
(
). 
, .

207

:
LRESULT CALLBACK KeyboardHook(int nCode,WPARAM wParam,LPARAM
lParam)
{ // . .
if((lParam>>31)&1)
// ...
switch(wParam)
{//
case VK_SHIFT: {iShiftKey=UP; break};
case VK_CONTROL: {iCtrlKey=UP; break};
case VK_MENU: {iAltKey=UP; break};
}
else// ...
switch(wParam)
{//
case VK_SHIFT: {iShiftKey=DOWN; break};
case VK_CONTROL: {iCtrlKey=DOWN; break};
case VK_MENU: {iAltKey=DOWN; break};
}
//
switch(KEYBLAY)
//

{
case 1: // Alt+Shift
{
if(iAltKey==DOWN && iShiftKey==UP)
{
vfBeep();
iShiftKey=RESET;
}
if(iAltKey==UP && iShiftKey==DOWN)
{
vfBeep();
iAltKey=RESET;
}
((iAltKey==UP && iShiftKey==RESET)||(iAltKey==RESET &&
iShiftKey==UP))
{
iAltKey=RESET;
iShiftKey=RESET;
}
break;
}

208


//
case 2: // Ctrl+Shift
{
if(iCtrlKey==DOWN && iShiftKey==UP)
{
vfBeep();
iShiftKey=RESET;
}
if(iCtrlKey==UP && iShiftKey==DOWN)
{
vfBeep();
iCtrlKey=RESET;
}
if((iCtrlKey==UP && iShiftKey==RESET)||(iCtrlKey==RESET &&
iShiftKey==UP))
{
iCtrlKey=RESET;
iShiftKey=RESET;
}
}
}
return 0;
}
:
void vfBeep()
{//
MessageBeep( 1);
MessageBeep( 1);//
}


,

(0,0). , 
.
wParam, , 
MOUSEHOOKSTRUCT, lParam. ,
, :
LRESULT CALLBACK MouseHook(int nCode,WPARAM wParam,LPARAM lParam)
{ //
if(wParam==WM_MOUSEMOVE || wParam==WM_NCMOUSEMOVE)

209

{
psMouseHook=(MOUSEHOOKSTRUCT*)(lParam);
if(psMouseHook >pt.x==0 && psMouseHook >pt.y==0)
if(bSCRSAVEACTIVE)
PostMessage(psMouseHook >hwnd,WM_SYSCOMMAND,
SC_SCREENSAVE,0);
}
return 0;
}
, 
, :
PostMessage(psMouseHook >hwnd,WM_SYSCOMMAND, SC_SCREENSAVE ,0).
, , , 
, .
:
extern "C" __declspec(dllexport) LRESULT CALLBACK
KeyboardHook(int,WPARAM,LPARAM);
extern "C" __declspec(dllexport) LRESULT CALLBACK
MouseHook(int,WPARAM,LPARAM);



. File New: 
Console Wizard Ok.
Source Type
C++. . 
.

. 
. .
( MainWnd ):
BOOL InitApplication(HINSTANCE hinstance,int nCmdShow)
{ //
WNDCLASS wcx; //
wcx.style=NULL;
wcx.lpfnWndProc=MainWndProc;
wcx.cbClsExtra=0;
wcx.cbWndExtra=0;

210


wcx.hInstance=hinstance;
wcx.hIcon=LoadIcon(hinstance,"MAINICON");
wcx.hCursor=LoadCursor(NULL,IDC_ARROW);
wcx.hbrBackground=(HBRUSH)(COLOR_APPWORKSPACE);
wcx.lpszMenuName=NULL;
wcx.lpszClassName="HookWndClass";
if(RegisterClass(&wcx)) //
{
MainWnd=CreateWindow("HookWndClass","SSHook", /* */
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,CW_USEDEFAULT,
CW_USEDEFAULT,CW_USEDEFAULT,
NULL,NULL,hinstance,NULL);
if(!MainWnd)
return FALSE;

return TRUE;
}
return false;
}
,
:
wcx.hIcon=LoadIcon(hinstance,"MAINICON");
, 
(*.res), MAINI
CON.
, 
, . 
:
LRESULT CALLBACK MainWndProc(HWND hwnd,UINT uMsg,WPARAM wParam,
LPARAM lParam)
{//
switch (uMsg)
{
case WM_DESTROY:{PostQuitMessage(0); break;}
case MYWM_NOTIFY:
{
if(lParam==WM_RBUTTONUP)
PostQuitMessage(0);
break; //

211

}
default:
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
return 0;
}

:
,
(, )? 

. :
void vfSetTrayIcon(HINSTANCE hInst)
{ // Tray
char* pszTip=" ";
// Hint
NotIconD.cbSize=sizeof(NOTIFYICONDATA);
NotIconD.hWnd=MainWnd;
NotIconD.uID=IDC_MYICON;
NotIconD.uFlags=NIF_MESSAGE|NIF_ICON|NIF_TIP;
NotIconD.uCallbackMessage=MYWM_NOTIFY;
NotIconD.hIcon=LoadIcon(hInst,"MAINICON");
lstrcpyn(NotIconD.szTip,pszTip,sizeof(NotIconD.szTip));
Shell_NotifyIcon(NIM_ADD,&NotIconD);
}

( NotIconD.uID) 
( NotIconD.uCallbackMessage). 
:
#define MYWM_NOTIFY (WM_APP+100)
#define IDC_MYICON 1006

(NotIconD.hWnd=MainWnd):
case MYWM_NOTIFY:
{
if(lParam==WM_RBUTTONUP)
PostQuitMessage(0);
break; //
}

.

212


:
void vfResetTrayIcon()
{//
Shell_NotifyIcon(NIM_DELETE,&NotIconD);
}



:
LRESULT CALLBACK (__stdcall *pKeybHook)(int,WPARAM,LPARAM);
LRESULT CALLBACK (__stdcall *pMouseHook)(int,WPARAM,LPARAM);
DLL 
:
hLib=LoadLibrary("SSHook.dll");
(hLib HINSTANCE hLib)
:
(void*)pKeybHook=GetProcAddress(hLib,"KeyboardHook");
(void*)pMouseHook=GetProcAddress(hLib,"MouseHook");
.
SetWindowsHookEx:
hKeybHook=SetWindowsHookEx(WH_KEYBOARD,(HOOKPROC)(pKeybHook),hLib,
0);
hMouseHook=SetWindowsHookEx(WH_MOUSE,(HOOKPROC)(pMouseHook),
hLib,0);
(hKeybHook hMouseHook HHOOK hKeybHook; HOOK
hMouseHook;)
( 
, ). 
. DLL.
, .
( ), 
.
. 
DLL.
:
UnhookWindowsHookEx(hKeybHook);
UnhookWindowsHookEx(hMouseHook); //
FreeLibrary(hLib);

213

214

WinMain
WinMain
,
, . 
:

WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,LPSTR


lpCmdLine,
int nCmdShow)
{
MSG msg;
//
hLib=LoadLibrary("SSHook.dll");
if(hLib)
{
(void*)pKeybHook=GetProcAddress(hLib,"KeyboardHook");
hKeybHook=SetWindowsHookEx(WH_KEYBOARD,(HOOKPROC)(pKeybHook),
hLib,0);//
(void*)pMouseHook=GetProcAddress(hLib,"MouseHook");
hMouseHook=SetWindowsHookEx(WH_MOUSE,(HOOKPROC)(pMouseHook),
hLib,0);
//
if (InitApplication(hInstance,nCmdShow))
//
{
vfSetTrayIcon(hInstance);//
while (GetMessage(&msg,(HWND)(NULL),0,0))
{//
TranslateMessage(&msg);
DispatchMessage(&msg);
}
//
UnhookWindowsHookEx(hKeybHook); //
UnhookWindowsHookEx(hMouseHook);
FreeLibrary(hLib);// DLL
vfResetTrayIcon();//
return 0;
}
}
return 1;
}

.

A B
pureC. , A
? ?
C++
, 
( 
).

()
, ,
.
: VMT.
,
TV ( ,
)
C++, 
()
, C++ 
.
, : 
(, 
) .
C++ !
(

) (
).
() ,
.
,
, ( shutdown
destroy TV).
( 
), ,

215

, 
. 
!

, , :
class PrintFile
public:
PrintFile(char name[]) (GetFileName(name, MyExt())); virtual
const char *MyExt() return "xxx";
;
class PrintAnotherTypeOfFile :public PrintFile
public:
PrintAnotherTypeOfFile(char name[]) :PrintFile(name) const char
*MyExt() return "yyy";
;
:
class PrintFile
enum Init_ Init; // protected:
;
PrintFile(Init_).
,
, , 
:
bool construct(char name[])
return (GetFileName(name,MyExt()));
public:
//...
PrintFile(char name[]) construct(name); virtual const char
*MyExt() return "xxx";
;
class PrintAnotherTypeOfFile :public PrintFile
//... ( )
public:
//... ; "" ,
;
//...
PrintAnotherTypeOfFile(char name[]) :PrintFile(Init)
construct(name);
const char *MyExt() return "yyy";
;

216

NAN?
, 
NonaNumber. ( )
, .00__00 (
).
_:

SNAN Signalling NAN ( )


=0

QNAN Quiet NAN ( )


= 1.

SNAN FPU ,
, 
.
QNAN=11__11.100__00 ( 
), FPU
, 0 0, 0 ,
FSQRT, FYL2X ,
.. , (
CW, IM=1). 
(Int 10h) .
 
(, 

).
longjmp
?
,

(, 
). 
volatile.
longjmp jmp_buf, setjmp 
( ), .
setjmp longjmp , 
.
jmp_buf (
setjmp) ,
.

217

longjmp 
( ).
, 
.
(,
).
volatile 
, , 
...
?
, ,
, 
void*. 
:
int i; int f();
struct X int i; int f(); x, *px = &x;
int *pi = &i; i = *pi;
int (*pf)() = &f; i = (*pf)();
int X::*pxi
= &X::i; i = x.*pxi;
int (X::*pxf)() = &X::f; i = (px >*pxf)();
for, while?
for while:

for
;

continue ,
for(int i = 0; i < 10; i++) ... continue; ...

int i = 0; while(i < 10) ... continue; ... i++

218

delete NULL? delete[]var


new var[]? delete data; delete data?

delete NULL ( free(NULL)) ;

delete[] new, delete new[]


.

 ;

delete (
)
,
core dump, ,
;

new data1; delete data1;


new data2;
delete data1; delete data2;
?
...
: 
, 
, ,
( ),
().
:

NULL?
, NULL 0
.

struct String1 ... char *ptr; ...


String1 &operator = (String1&); ... ;
struct String2 ... char array[lala]; ... ;
String2 
String2::array 
, String1::operator = ptr.
.

Ho 
(, printf) 
0 ( NULL
0L).

,
.
, 
:

, NULL 
: int,
, 0, NULL .

struct C0 C0 &operator = (C0 &src) puts("C0=");


return *this; ;
struct C1 :C0 C0 & operator = (C0 &src) puts("C1="); return

219

*this;
;
int main()
C1 c1, c2; c1 = c2;
,
`C1::operator=(C1&)' ( `C1::operator=(C0&)'),
, , C0::operator=(C0&).
,
, :
, xcvvxx:svvsvv.
?
class A;
extern "C" int ClassMetod_Call2Asm (A*, ...);
class A
int Call2Asm(...) return ClassMetod_Call2Asm(this, ...);
;
Cpp . ,
asm ...

220

1 3 , 

, stklen ( C++),
stklen SP.
4 , callback,
; , .
! ,
? asm ?
asm'a . 
asm '#pragma aux ...'.
:
#pragma aux DWordsMover = \
"mov esi, eax",
\
"mov edi, ebx",
\
"jcxz @@skipDwordsMover", \
"rep movsd",
\
"@@skipDWordsMover:",
\
parm [ebx] [eax] [ecx] modify [esi edi ecx]
void DWordsMover (void* dst, void* src, size_t sz);

Watcom:
#pragma aux var "_*";
var var. 
extern C .
, a 
. cdecl 
.
:
extern "C" int cdecl my_func();
stack overflow ?
:
1.

16Cbit OS/2 executable Watcom


DOSCALLS.LIB. OS/2.
?
. LIB286 LIB386
OS2286.LIB. , . DOSCALLS.LIB
.
BC
, .
ASMC. C
?
RTL C++ 3.1 
. :

2. ( 
);

#define I asm
//........
I or si,si
I jz m1
I mov dx,1 m1:
I int 21h

3. (, 
)
4. callback  (, 
);

..

221

'B' (via Tasm) aka '#pragma inline'.


, :
read _read (), .
, (3.1, ) 
B.
, 
, .
BC++ 3.1 Null
pointer assignment?
 ,
.
:

, .

:
char *string; gets(string);

,
NULL , .
:
FILE *f = fopen("gluck", "w"); putc('X', f);
Tiny, Small,
Medium.
: 
.
main
( ) 
.
HELPME!.DOC Watch
:
*(char*)0,4m
(char*)4
, 
.
,
.

222

BC (CtrlCF9) ,
BC, . ?
BWCC,
BWCC 
. :
#define _BEST EnableBWCC(TRUE); \
EnableCtl3d(TRUE); \
EnableCtl3dAutosubclass(TRUE)
InitMainWindow :
_BEST;
.
 OWL'
. 
:
int OwlMain(int /*argc*/, char* /*argv*/[])
int res;
TRY res = App().Run();
CATCH((xmsg &s)
//
MessageBox(NULL, "Message", s.c_str());
return res;
BC++
, inactive scope?
. :
bcc v is.cpp
=== Cut ===
#include <iostream.h>
void a()
int b = 7;
cout << b << endl;
void main()
a();
=== Cut ===
TD. F8, a().
inspect b. , . 
cout, a()
b.  inactive scope.

223

, .
, ,
, malloc', sizeof(struct ...) ,


new:
#define tmalloc(type)
((type*)malloc(sizeof(type)))
#define amalloc(type, size) ((type*)malloc(sizeof(type) * (size)))
, define (size) + 1,
.
. malloc() 
, 
:
body = malloc(sizeof(*body));
malloc().
Ho , void* type*
( ,
).
void* 
. , C++ 
C++ malloc() free(),
hosted ++ .
:
#ifdef __cplusplus
# define tmalloc(type) (new type)
# define amalloc(type, size)
(new type[size])
#else
# define tmalloc(type) malloc(sizeof(type))
# define amalloc(type, size) malloc(sizeof(type) * (size))
#endif
, . 
:
#ifdef __cplusplus
# define tmalloc(type) (new type)
# define amalloc(type, size)
(new type[size])
# define del(var) delete(var)
#else
# define tmalloc(type) ((type*)malloc(sizeof(type)))

224


# define
(size)))
# define
# define
((var) =
#endif

amalloc(type, size) ((type*)malloc(sizeof(type) *


del(var) free(var)
vmalloc(var)
malloc(sizeof(*(var))))

, , ,
c ? , ,
ff_attrib, findfirst findnext, .
?
done = findfirst("*.*", &onlydir, FA_DIREC);
while(!done)
cout << onlydir.ff_name << endl;
done = findnext(&onlydir);
, MS DOS. , 
, . 
, . ff_attrib
. findfirst/findnext.
: fopen(FPtr, "w"). ,
?
fopen (FPtr,"wb");
...
cprintf x = 80, y = 25
(
)
. ,
?
Ctrl+F1 _wscroll IDE. ,
printf , 
.
ANSI C?
, ANSI C . Turbo
:
#include <conio.h>
void main(void) clrscr();
ANSI ESC
:
#include <stdio.h>
#define NROWS 2*25 /*

225

226

void main(void)
short i;
for(i = 0; i < NROWS; i++) puts("");
Ho .

VESA,
... ?

(
8).
, .
, 33h ,
.

, VESA.
, Logitech MouseWare 6.3
, 
.
Try & Bye?
Win32 :
HKEY_LOCAL_MACHINE\SOFTWARE\IBM\IBM VisualAge for C++ for Windows
Demo\demo

HKEY_LOCAL_MACHINE\SOFTWARE\IBM\IBM VisualAge for C++ for


Windows\3.5
OS/2 \os2\system\epfis.ini 
INI :

EPFINST_IBM VisualAge C++ for OS/2_TRIAL_COPY_0001 



EPFINST_IBM VisualAge C++ for OS/2_5622 679_0001

ApplicationName

IBM VisualAge C++ for OS/2 TRIAL COPY

IBM VisualAge C++ for OS/2

cppexit.dll exit.dll.

IVBContainerControl?
IVBContainerControl .
IVSequence, IVBContai
nerControl.
, IVSequence * IVBContainer
Control::items . items .
part VB .VBE?
.VBE
( ) VB?
.VBE, Part .
.\Samples\VisBuild\vbSample\*.VBE
, , 
.
?
..\Sample\VisBuild\
Doodle\ClrDlg.VBB.
VAC++ WPS WF?
. WPS,
 FileBar.
, .
VB 16 MB.
, N
. VisualBilder/PartEditor?
Ha Ibm' VAC++
. vbtimer.zip ~30 .
.vbb Visual Builder.
?
VbLoad.Dat
, , 
Visual Builder , (
) VbBase.Vbb, VbDax.Vbb e.t.c (
IVB Win DDe4Vb Os/2).

227

, , 
VBPATH.
?
. ,
.
10 ,
?
(
) , 
.
WIN9 p, WATCOM. He
. ?
\Windows\Start Menu\Programs 
. .lnk .

.
, ?

, , 
,
, .
, ,
 .
p pp 
p . 
, , 
3 .
, , ?
, 10
, 
VIEW , Windows 
WHELP *.HLP,
, 
.

228

IDE, , ,
?
IDE , Windows OS/2.
.
IDE Multi
Edit, .
, ?
:
#include <stdio.h>
main()
puts("Hello, world");
:
wcl hello.c DOS/16
wcl386 /l=dos4gw hello.c DOS4GW
, ,
, ?

?
WLSYS
TEM.LNK, , 1
2 , ,
.
16
32 . ,
.
,
, , ?

, , 
, .
,
, , _
, ?
:
#pragma aux ASMFUNC "_*";
:
#pragma aux (ASMFUNC) foo;

229

230

#pragma aux (ASMFUNC) bar;


, ^, 
, , :
#pragma aux myfunc ^; 
MYFUNC.

C
.
exeC . ?
DOS4GW/PRO. DLL.
PharLap TNT, .

, ,
_
?
cdecl,

.

, . DPMI 
() ,
.
TNT.

, Watcom
, ?
cdecl.
:
extern void cdecl dummy( int );
?
:
unsigned short swap_bytes ( unsigned short word );
#pragma aux swap_bytes = "xchg ah, al" \
parm [ ax ] \
value [ ax ];
parm ,
value .
. modify
( ) ,
.
. ,
, .
, .
ZINC 3.5, C . ,
C ?
. 4.0,
.


/ . ?
, 

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

VESA .
, : _SVGAType,
:
"extern "C" int _SVGAType;",
(!) _setvideomode :
"_SVGAType = 1;"
exeC?
WLINK, .
name ...
system ...
debug all
option ...

231

option ...
option ...
...
file ...
file ...
...
libpath ...
library ...
:
wlink name myprog system dos4gw debug all file myprog
ms2vlink ?
. 
LINK WLINK.
_wd_?
, WVIDEO, 
.
10.
NLM'. ?
WATCOM 10.0. NLM SDK
. WC <= 9.5, NLM SDK .
// :
// ( wclink.lnk )
// system netware
// Debug all
// opt scr 'Hello, world'
// OPT VERSION=1.0
// OPT COPYR 'Copyright (C) by me, 1994'
#include <conio.h>
void main( void )
cprintf( "Hello, world!\n\r" );
ConsolePrintf( "Hello, World just started!\n\r" );
RingTheBell();
OS/2 16C, p C
DOSCALLS.LIB. ?
. os2286.lib.
. doscalls.lib, 
.

232

pipe?
OS/2?
vdmserv.exe, 
wd /tr=vdm vdmserv , . 
? , 
.
32C PM
(/d2), rc ,
. CC
?
wstrip' .sym 
. .sym , p
.
SYM:
wcl386 /d2 /"op symf" /l=os2v2_pm
WATCOM 4 p p 8 , 8
p 16 , ?
, .
SET WCGMEMORY=4096,
.
, Windows C++ 
.
pipe gcc bcc. Watcom'e
?
stdout stderr?
. dup() .
?
C callback,
?
C++ : set_new_handler().
DLL ?
, DLL
EXE' p (static). DLL
(dynamic).

233

DLL OS/2 . ?
?
, declare func dll test.lnk.
, dll,
. API OS/2:
DosLoadModule DosQueryProcAddr DosFreeModule.
:
exe.c:
#define INCL_DOSMODULEMGR
#include <os2.h>
#define DLLNAME "DLL"
PFN Dllfunc;
char FuncName[]="RegardFromDll_";
char LoadError[100];
void main()
HMODULE MHandle;
DosLoadModule( LoadError, sizeof( LoadError ), DLLNAME, &MHandle
); DosQueryProcAddr( MHandle, 0, FuncName, &Dllfunc );
(*Dllfunc)();
DosFreeModule( MHandle );
dll.c
#include <stdio.h>
void RegardFromDll( void )
printf( "This printed by function, loaded vs DLL\n" );
DLL, bd, 
.obj , DLLstart. :
wpp386 bd 4s ox dll.cpp
p ?

, :
void foo( int bar, char* )

#pragma off(unreferenced)
:
#ifndef NU
#ifdef __cplusplus
#ifdef __BORLANDC__
#define NU( ARG ) ARG
#else

234

#define NU( ARG ) (void)ARG


#endif
#else
#define NU( ARG ) ARG=ARG
#endif
#endif
, , p
/*ARGSUSED*/ .
, watcom'e ?
TFM. _grow_handles(int newcount).
16C OS/2
?
newfiles p.
C Dev.Toolkit for OS/2 Warp WC10.0
. definition of macro '_Far16' not identical previos
definition. ?
 IBMCPP D_IBMCPP
#define #include <os2.h>.
10.5a d_IBMCPP, d_IBMCPP_=1.
: printf (*);, . ?
ansi, 
stdin/stdout/stderr ,
stdout/stdin.
 p stdout 
, .
'\n', flush line
buffered .
: '\n' 
. fflush(stdout) , .
setbuf(stdout,NULL) setvbuf(stdout,
NULL,_IONBF,0).
C DOS4GW, D00M?
. 
:
copy /b dos4gw.exe + a.exe bound.exe

235

( 10.0) 
dos4gw/pro Tenberry Software.
. dos4g/link 
/ EXE. 
WATCOM.C uuencode .
DOS4GW, (DOS4GW 1.97),
Pro (DOS4GW Professional). DOOM,
HERETI, HEXEN, WARCRAFT2 .., . 
2 Pro 1.97
,  .

236


?
dos4gw.
, 0xC000 
0x000C0000.
, VGA .
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void main( void )

( ). 
, PMWBIND
PMODE/W.

unsigned i;
for( i = 0; i < 256; i++)

dos4gw.exe
, WATCOM patch level [...]. 
:

char c;
c = *(char*)( 0x000C0000 + i );
putchar( isprint( c ) ? c: '.' );

copy /b dos4gw.exe myexe.exe mynewexe.exe


DOS/4GW 1.95. 1.97
linexe .

, Pharlap ?
wd /tr=pls file.exe,

DOS/4GW.  
pmwbind.exe PMODE/W ( 1.16 
DOS/4GW, 
4GW/PRO); dos4g/link,
.

wd /tr=rsi file.exe
dos4gw.

4GWPRO ( 
pmwbind.exe dos4g/link), DOS/4GW ( 
4grun.exe, wd.exe ), PMODE/W.
DOS4G 4GBIND.EXE (
DOS4G).
dos4gw?
_memavl _memmax
. ?

, . 
RAM DMPI, 
.

dos4gw Pharlap? ?
p.
dos4gw , p .
RUN386.EXE?
p C?
p p. Ho .
DOS4GW ( 200 ),
, ?
PMODE, 
, Watcom PMODE/W, 
DOS4GW, 9 , .
, 
 dos4gw, pmode/w
.

237

100% c dos4gw , ,
, , D00M.
, 100% , 
DOS/4G ,
DOS/4GW int 21h, ah = 0xFF.
DOS/4GW PMODE/W (
) .
DOS/4G :

WDOSX ( 0.94, size ~12 Kb)

DOS32A ( 4.30, size ~20 Kb)

DOS4GW DOS4GW PRO?


DOS4GW:

.EXE ,
(16 ),
(32 )

DPMI
( 303h allocate callback)

TSR'

DLL, freeware

4GWPRO

DPMI 1.0

DLL

TSR

DOS4G:

.EXE'

DLL

238

, 
(VMM virtual memory manager) 
DPMI 4GWPRO.
4GWPRO ?
, .
4GWPRO.
.

.

.

ACMAIN.EXE,

DESCENT.EXE,

HB5.EXE,

HEROES.EXE

1.97 . : 217764 .

ABUSE.EXE,

BK.EXE,

HEXEN.EXE,

ROTT.EXE,

TV.EXE (Terminal Velocity)

1.97 VMM DPMI.


: 157268 .

ACRODOS.EXE (Acrobat reader for DOS)

1.97 VMM, DPMI.


: 203700 .

D4GRUN.EXE ( Watcom 10.0)

1.96 VMM, DPMI ( 


DOS4G, 4GWPRO). : 154996
.

239

DOOM2.EXE

1.95 VMM DPMI.


: 152084 .
, DOS4GW
4GWPRO?
COPY /B 4GWPRO + OLD.EXE NEW.EXE
4GWPRO VMM,
16 ?
:
00000247
0 3
???
00000247:
4
1 VMM ., 0 .
00000247:
5
???
00000247:
6
1
00000247:
7
???
1.97 217764 .
0001BFF8: (4 ) .
DLL c DOS4GW?
, DLLPOWER.
SimTel' dllpr251.zip, dllpr254.zip
.
C,
, ?
,
. int > short.

240

BC, 
, ,
.
, , random(num) 
, stdlib.h, 
(rand() % num).
,
OWL TVision?
OWL ,
, . 
TVision .
diff TV GNU C++ (
GVISION. , ,
TV 32 .
TV Watcom C++.
dos4gw TV 1.0.

+makefile. 
.
inline
, ?
. , 
.asm .
11 a la Borland:
_asm ...

,
BC , ?
, BC, 
, 
, ,
BC, .

.
, gettime() dos_gettime(),
findfirst dos_find_first, .

aCy aoe _AX Borland?


, a
_AX readonly, :
=== Cut ===
short reg_ax ( void ) ;
#define _AX
reg_ax()
#pragma aux
reg_ax = \
value [ax]
#if defined( __386__ ) || defined( __FLAT__ )
int
reg_eax ( void ) ;
#define _EAX reg_eax()
#pragma aux
reg_eax = \

241

value [eax]
#define
rAX reg_eax() //
#else
#define
rAX reg_ax()
#endif
=== Cut ===
,
( inlineasm).
,
, p
( ). ,
. ?
Ha :

obj >wdisasm >.asm >wasm >

242

gcc,
, (
, Win32 cygwin) 
Win32 , , 
djgpp,
rsxnt.
, ,
. .

, ( p
p ),
, , 
, 
.
Watcom ?
asm'a . 
asm #pragma aux .... :

obj
wlink'.

#pragma aux DWordsMover = \


"mov esi, eax", \
"mov edi, ebx", \
"jcxz @@skipDwordsMover", \
"rep movsd", \
"@@skipDWordsMover:",
\
parm [ebx] [eax] [ecx] modify [esi edi ecx]
void DWordsMover(void* dst, void* src, size_t sz);
11.0 asm{}.

tasm 3.2,
tasm 4.0, ,
...
TASM32 5.0 ( 32 bits)
, , ..

.

WRC.DLL Optima 1.0 WRC.EXE 
Watcom 11.0 .
C (C++) ? : Watcom C++
Borland C++? ?!
.
, . , 

C++, .
Win32 y Borland C++ Builder, 
y 
. BC++ 3.1 ,
, .

BC
, .
ASMC.
?
RTL BC++ 3.1 
, :
#define I asm
//........
I or si,si
I jz m1
I mov dx,1
m1:
I int 21h
..

243

B. ,
: read
_read (), .
, (3.1, ) 
B. ,
, 
.
/
: char* myview() { char s[SIZE]; ... return s; }
static char s[SIZE];
() , 

 .
?
( 
) undefined behavior. , 

. (
), , ,
__asm VC++ 
 . undefined behavior
, .
undefined behavior
. , , , printf 
() , 

 ( !).
, for
, ( 
!) .
, ,
define:
C++ 
for . 
, 
:
#define for if(0);else for
BC++ if(0) :

244


"Condition is always false"
#pragma warn ccc

const ?
, .
const ,
mutable.
class Bart
{
private:
mutable int m_iSomething;
public:
void addToSomething( int iValue ) const
{
m_iSomething += iValue;
}
Bart()
{
m_iSomething = 0;
}
};
const Bart bartObject;
bartObject.addToSomething( 8 );
.
?
struct a { static int i; };
int a::i; // ?
int main() { a::i = 11; return 0; }
:
struct b { int n; b(int i) :n(i) {} };
struct a { static b i; };
b a::i(0);
int main() { printf("%i\n",a::i.n); return 0; }

. ?
, ,
? ?
?

245


new:
#define tmalloc(type)
((type*)malloc(sizeof(type)))
#define amalloc(type, size) ((type*)malloc(sizeof(type) * (size)))
, define (size) + 1,
.
. malloc() 
, 
:
body = malloc(sizeof(*body));
malloc().
, void* type* (
,
).
C void* 
. , C++ 
C++ malloc() free(), hosted ++ 
. :
#ifdef __cplusplus
# define tmalloc(type)
(new type)
# define amalloc(type, size) (new type[size])
#else
# define tmalloc(type)
malloc(sizeof(type))
# define amalloc(type, size) malloc(sizeof(type) * (size))
#endif
?
( ) .
:
void swap(int& i, int& j)
{
int tmp = i;
i = j;
j = tmp;
}
int main()
{
int x, y;
// ...

246

swap(x,y);
}
i j x y
main. , i x. x x, x.
, i, x, .

. , ,
, . i
x , , x.
i++, , x.
, , , x,
. , 
, ,
, , & ( )
, , ,
* (). ,
i (*p), p x
(.., 
: i++ (*p)++, i = 7 *p = 7).
: 
,
.
. . .
?
(, 
).
: , , ,
, . 
lvalue (left value , 
).
, ?

() .
, . 
, f() = 7 . , a
Array, a[i] = 7 
, a[i]
Array::operator[](int), 
Array:

247

class Array {
public:
int size() const;
float& operator[] (int index);
// ...
};
int main()
{
Array a;
for (int i = 0; i < a.size(); ++i)
a[i] = 7; // Array::operator[](int)
}
,
?
.
.
, , 
, .
, ,
. ,
. : , .
, const ,
int* const p ( const, const int* p). 
,
.
,
?
, , 
.
, 
. , 
(public) .
, .
, 

. / 
,
(NULL).

248


.
: 
, 
.
++, , 
, , .
.., , 
(programmers should write code in the language of the problem rather than
the language of the machine).
?
, 
, . ,
#define, 
(!) 
( ).

?

, void, 
, .
, , ,
void 
. .
, ,

( , 
, , ,
void*.

).
, 
. ++ , 
. ,
,
#define 
.

249

?
#define ?
#define .
#define , (inline)
, 
. 
,
, :
// , ( ) i
#define unsafe(i) \
( (i) >= 0 ? (i) : (i) )
// , i
inline
int safe(int i)
{
return i >= 0 ? i : i;
}
int f();
void userCode(int x)
{
int ans;
ans = unsafe(x++); // ! x
ans = unsafe(f()); // ! f()
ans = safe(x++); // ! x
ans = safe(f()); // ! f()
}
, , 
, .
; , 
.
(static
initialization order fiasco)?
.

++. ,
,
main().

250

, x y, 
, x.cpp y.cpp.
y  x.
. .
, 
. , x.cpp
, .
y.cpp, 
y x, . .., 
y x, x .
: 
/ , int char*. ,
float, 
. , 
.
?
, , 
.
, Fred Barney. 
Fred, x, Barney,
y. Barney goBowling() x.
x.cpp x:
// File x.cpp
#include "Fred.hpp"
Fred x;
y.cpp y:
// File y.cpp
#include "Barney.hpp"
Barney y;
, Barney::Barney() 
:
// File Barney.cpp
#include "Barney.hpp"
Barney::Barney()
{
// ...
x.goBowling();
// ...
}

251

, y , x, 
50% , x y .
,
Fred x, 
x(), Fred .
// File x.cpp
#include "Fred.hpp"
Fred& x()
{
static Fred* ans = new Fred();
return *ans;
}
,

, new Fred()
: x(). 
Fred (, 
ans). x 
x():
// File Barney.cpp
#include "Barney.hpp"
Barney::Barney()
{
// ...
x().goBowling();
// ...
}
, 
Fred .
,
Fred .
: 
/ , int char*. ,
float, 
. , 
.

?
, X, 
Fred:

252


// File X.hpp
class X {
public:
// ...
private:
static Fred x_;
};
, :

// File X.cpp
#include "X.hpp"
Fred X::x_;
, Fred
X:
void X::someMethod()
{
x_.goBowling();
}
,    
, Fred . ,
 X someMethod() 
, 
, X::x_,
someMethod(), .
, ( 
), X::x_ 
:
// File X.hpp
class X {
public:
// ...
private:
static Fred& x();
};
, :
// File X.cpp
#include "X.hpp"
Fred& X::x()
{
static Fred* ans = new Fred();
return *ans;

253

}
x_ x():
void X::someMethod()
{
x().goBowling();
}


X::someMethod(), static Fred&. 
,
( ),
X::x() :
X::someMethod():
void X::someMethod()
{
static Fred& x = X::x();
x.goBowling();
}
: 
/ , int char*. ,
float, 
. , 
.

254

b 
, a:
void userCode()
{
Fred a;
Fred b;
// ...
}
?
:
.
:
a[9], a[8], ..., a[1], a[0]:
void userCode()
{
Fred a[10];
// ...
}
?
.

, ?
.

.
Fred Fred::~Fred().
, 
.

?
.

, 
(,
).


. , Lock 
, .
new,
delete.
. 
dtor.

?
, : 
.

?
!

} , 
. ,
; .

. ! ...

255

,
?
?
!
, () 
File .
, f File ,
f (..,
}):
void someCode()
{
File f;
// ... [ f] ...
// < f
// ... [ f] ...
}
.
: .
, .
?

{...}, :
void someCode()
{
{
File f;
// ... [ f ] ...
}
// ^ f !
// ... [ f ] ...
}
,
?

{...} .
 , 
, , .
: !

256

close()  File,
. 
,  fileHandle_ 
, 1, ,
fileHandle_ 1.
class File {
public:
void close();
~File();
// ...
private:
int fileHandle_;
// fileHandle_ >= 0 /
};
File::~File()
{
close();
}
void File::close()
{
if (fileHandle_ >= 0) {
// ... [ ] ...
fileHandle_ = 1;
}
}
, File
, fileHandle_ 1 (..,
).
, , 
, fileHandle_ 1.
,
new?
, .
,
new,
delete, . , 
new:
Fred* p = new Fred();

, File,
close(). close(). ,

257

Fred::~Fred() 
, :
delete p; // p >~Fred()
,
, Fred. : delete p
: .
new (placement new)
?

new. 
.
, new:
#include <new> //

#include "Fred.h" // Fred

258

(alignment), . 
,
. Fred 
, new 
, ( ,
(alignment), , 
new). .

. :
void someCode()
{
char memory[sizeof(Fred)];
void* p = memory;
Fred* f = new(p) Fred();
f >~Fred();

void someCode()
{
char memory[sizeof(Fred)]; // #1
void* place = memory;
// #2
Fred* f = new(place) Fred(); // #3
// f place
// ...
}
#1 sizeof(Fred) , 
Fred. #2 
place, ( 
,
; ).
#3
Fred::Fred(). this Fred
place. , place.
: new, 
, , 
. , 
, ,
Clock .
: new
,


//
}
, 
.
,
C ?
. (
new.
(, ,
) 
.
:
class Member {
public:
~Member();
// ...
};
class Fred {
public:
~Fred();
// ...
private:

259

Member x_;
Member y_;
Member z_;
};
Fred::~Fred()
{
// z_.~Member()
// y_.~Member()
// x_.~Member()
}
,
?
. (
new).
(, 
, )
. 
. 

.
class Member {
public:
~Member();
// ...
};
class Base {
public:
virtual ~Base(); // [20.4]
// ...
};
class Derived : public Base {
public:
~Derived();
// ...
private:
Member x_;
};
Derived::~Derived()
{
// x_.~Member()

260

// Base::~Base()
}
: 
.
,
, .
C
(
) ,
 . 
, &, malloc()
. (malloc
, , 
, 

.)

. ,
;
.
, 
, 
. 
,
,
, .
?
0, , 
. ,
, 
, , ,
0 
.
, :
char *p = 0;
if(p != 0)
, , ,
,
0 . , 

261

UNIX execl 
, 
. , 
, 0
.
execl("/bin/sh", "sh", " c", "ls", (char *)0);
(char *), ,

0. (, UNIX 
.)
, 

, 
, ,
. 
, , , 
, 
.
, 

, ANSI ,
, , . (,
.)
NULL #define?
, 
. NULL
<stdio.h> <stddef.h> 0. , 
0 0 
NULL , .
; NULL
0, 
.

NULL ( 0).
#define NULL ,

?

() , .

262


, ,
"0" NULL.
, NULL 0 ,

, ( )
0,
.
NULL : #define NULL ((char
*)0). , NULL
?
, . , , 

. #define 
, 
char,
, :
FILE *fp = NULL;
.
, ANSI C NULL:
#define NULL ((void *)0)
(
, 
, )
, NULL (,
ASCII NUL).
#define Nullptr(type) (type *)0,

, 
. . 
.
, ,
, 
, 
.

263

if(p)
, ?
?
(
if, while, for do &&, ||, ! ?) false ,
, true 
. , :
if(expr)
expr , 
, :
if(expr != 0)
, p
expr, :
if(p)

if(p != 0)
, , ,

. ,
.
.
! :
!expr

expr?0:1
,
if(!p)

if(p == 0)
if(p) , 
.
NULL 0 ,
?
, NULL
, ,
. ,
, NULL 0, , 0

264

#define 0
NULL. .
, NULL 0 0 

, . NULL ( 
0 )
, ; 
( , 
) , 0.
NULL , .
, 
.(ANSI NULL #define
(void *)0. NULL ,
). 
NULL , ASCII (NUL). 
, :
#define NUL '\0'
NULL ( 0) ,
NULL , ,
?
.
 , , ,
NULL, . : 
, 0, , 
, . NULL 
.
. , NULL 0, C
?
null NULL 
:
1. .
2. ( )
, 
. 
.
.
3. ,
0.

265

4. NULL #define 0
(void *)0.
5. ASCII (NUL), ,
,
.
6. , , , ("").
?
?
, 
, .
, 
, .. ,
.
(NULL) , ,
 .
if(p == 0) ,
p , 0 . ,
, null (
).
,
(, nil, ), 
. nil 
, ,
. ,
nil 0. , 
, 0
, , , 
. , ,
0 .
.

:
1. , 
0 NULL.
2. 0 NULL
, ,
.

266

, ,
,
?
, ,
,
( ) 
, ,

, .
, ? 
, 
. , 
, (
calloc. ,
, 
, 
int. ( 0 
nil,
).
, C

?
Prime 50 07777, 0 
, , PL/I. 
0, 0 , 
, TCNP (
),
, 
. Prime
, (char *) 
, (int *).
Eclipse MV Data General
( , ),
char * void * .
word * .
HoneywellBull
06000 .
CDC Cyber 180 48 ,
(ring), . 
0xB00000000000.

267


; <NIL,0>
( , <, > ) 
.
, 80*86 (PC)
16 32 
, , , 32 16
.
HP 3000
. char void, , ,
, int ( ..), 
.
null pointer assignment
( ). ?
MSDOS ,
,
.

. ,
20 0 , 
.
, char a[] char *a
. (, ,
.) .
char a[6]; ,
a. ,
a, 6 . , 
char *p; .
p
( ).
, [3] 
, .
p[3] , 
p, , 
3 , , , .

268


?

. 
, 
.

: , , 
( )
; . (
, sizeof, 
& .)

[], 
. , , [i]
a 
, p[i]
( ). x[i],
) *((x)+(i)).

?
,
. , 
:
f(a)
char a[];
,
, :
f(a)
char *a;

, . , 
; , 
,
/ , 
.

269

lvalue,
?
ANSI C lvalue,
.
sizeof ,
?
sizeof , 
.
C ,

. ,
, , 
.
C
?
, 
. ,
( 
malloc), (..
) , ,
, 
.
,
.
, mal
loc, .
,
5["abcdef"]. ?
, . 
, ,
a[e] *((a)+(e)), 
, , 
.
,
(Obfuscated C Contest)

270

,
,
, 
. (..
) , .

. ( ,
, pcc
pcc lint, 

.) :
int array[NROWS][NCOLUMNS];
f(array);

f(int a[][NCOLUMNS]) {...}

f(int (*ap)[NCOLUMNS]) {...} /* ap */


, , 

; .
,
, NROWS 
.  ,
NCOLUMNS ( 
3 , ).

, 
, , .
,
,
?
.
[0][0] :
f2(aryp, nrows, ncolumns)
int *aryp;
int nrows, ncolumns;
{ ... array[i][j] aryp[i * ncolumns + j] ... }

271

:
f2(&array[0][0], NROWS, NCOLUMNS);
, , , , 

ANSI C; (&array[0][0])[x] x >
NCOLUMNS.
gcc , 
, , 
.
?
. 
, 
.

. T 
, ;
.

, 
.
,
 int (*ap)[N]; N . 
, N , 

.
, ,
int array[NROWS][NCOLUMNS];
array &array?
ANSI/ISO , &array
, .
ANSI & &array 
, . ,
, ,
.. .
?
,
, 
. :

272

int **array1 = (int **)malloc(nrows * sizeof(int *));


for(i = 0; i < nrows; i++)
array1[i] = (int *)malloc(ncolumns * sizeof(int));
( , malloc 
, malloc .)
, ( 
),
:
int **array2 = (int **)malloc(nrows * sizeof(int *));
array2[0] = (int *)malloc(nrows * ncolumns * sizeof(int));
for(i = 1; i < nrows; i++)
array2[i] = array2[0] + i * ncolumns;

:
array[i][j].
, 
,  ,

:
int *array3 = (int *)malloc(nrows * ncolumns * sizeof(int));
, ,
, i,j array3[i*nco
lumns+j]. ( ,
, 
, .)
, :
int (*array4)[NCOLUMNS] =
(int(*)[NCOLUMNS])malloc(nrows * sizeof(*array4));,
,
.
, 
, ( ),
, 
, .

273



?
.
int array[NROWS][NCOLUMNS];
int **array1;
int **array2;
int *array3;
int (*array4)[NCOLUMNS];
,
:
f1(int a[][NCOLUMNS], int m, int n);
f2(int *aryp, int nrows, int ncolumns);
f3(int **pp, int m, int n);
, :
f1(array, NROWS, NCOLUMNS);
f1(array4, nrows, NCOLUMNS);
f2(&array[0][0], NROWS, NCOLUMNS);
f2(*array2, nrows, ncolumns);
f2(array3, nrows, ncolumns);
f2(*array4, nrows, NCOLUMNS);
f3(array1, nrows, ncolumns);
f3(array2, nrows, ncolumns);
, , , 
, , 
ncolumns
NCOLUMS:
f1((int (*)[NCOLUMNS])(*array2), nrows, ncolumns);
f1((int (*)[NCOLUMNS])array3, nrows, ncolumns);
, &array[0][0]
f2 .
, 
, , ,
, , ,
(
) .

274

: int realarray[10]; int *array = &realarC


ray[C1];, array ,

,
.
,
, .
, 
. , , ,
(,
 
).
char,
int,
int. ((int *)p)++; ?

, ; , 
,
rvalue, 
++. ( 
, pcc gcc
.)
, :
p = (char *)((int *)p + 1);

p += sizeof(int);
void **,
?
,
. void * 
,
, .
( 
), ,
void **  void *.
: char *answer; printf("Type someC
thing:\n"); gets(answer); printf("You typed \"%s\"\n", answer);
answer, gets ,
, ,

275

..  . ,
, answer. (
, ,
, answer .

,
:
#include <string.h>
char answer[100], *p;
printf("Type something:\n");
fgets(answer, sizeof(answer), stdin);
if((p = strchr(answer, '\n')) != NULL)
*p = '\0';
printf("You typed \"%s\"\n", answer);
, fgets() gets(),
, ,
, 
. ( , fgets()
\n, gets()).
malloc().
strcat. char *s1 =
"Hello, "; char *s2 = "world!"; char *s3 = strcat(s1, s2);

, 
.
string.
, 
( 
, ). 
, ,
, 
. 
malloc.
strcat ; 
. ,
:
char s1[20] = "Hello, ";
strcat (
s1), s3 .

276

strcat ,
char.
?
,
, , ,
.
,
.

UNIX . 
,
, , . ,
, ( 
, ), , 
 ( 
). stat().
, , ,
,

, ,
. 
, 
, , 
malloc(), (auto) . ,
:
char *f()
{
char buf[10];
/* ... */
return buf;
}
( , f() 
, 
):
static char buf[10];
,
malloc(),
?
, ANSI/ISO
void *,

277


. ( C ANSI/ISO, 
).

?
. malloc() , 
; 

ANSI.

, . 
() , 
, :
struct list *listp, *nextp;
for(listp = base; listp != NULL; listp = nextp) {
nextp = listp >next;
free((char *)listp);
}
, ,
:
listp = listp >next
nextp.
free() , ?
malloc/free
, 
.
?
.
,
.
, ,
, ?
. , , ,
malloc() free() (
).

278

malloc() ,

free(), ( C
)
malloc/free 
( ), 
malloc()
.

?
. 
.
, ,
,
ANSI/ISO ,
.

realloc()? ?
ANSI C (
realloc(...,0) ), 
, 
. realloc()
.
calloc malloc?
calloc
? free ,
calloc, cfree?
calloc(m,n) :
p = malloc(m * n);
memset(p, 0, m * n);
, , 
,
. free ( )
, calloc.
alloca
?
alloca , ,
, alloca.

279

, , alloca,
.
alloca ,
.
( 
),
, , , fgets(alloca(100), 100, stdin).
alloca ( ,
) ,
.
: a[i] = i++; ?
i++ i
, , i
.
int i = 7; printf("%d\n", i++ * i++);
, 49. ,
, 56?
++ 

,
. , 

.
, 
(
ANSI C). 
i 1.
,
. ,
( 
).
: int i = 2; i = i++;
i=2, 3, 4. ,
, 4?
(undefined) , 
.

280

, , ANSIC
,
, , 
( 
).
, , . , 
, .
,
? ,
?
,
. 
:
f() + g() * h() .
, 
, ,
.
&&, || ?
if((c = getchar()) == EOF || c == '\n')"
, ?: 
;
, .. .
,
i: : ++i : i++?

, ,
.
: int a = 1000, b = 1000; long int c =
a * b;
, 
,
/ 
long int.
, :
long int c = (long int)a * b;
, (long int)(a * b) 
.

281

ANSI C?
1983
(ANSI) X3J11, .
,
, 14 1989 .
ANS X3.1591989.
1990 .
ANSI C
++ (
). 
( 
). ANSI C 
.
(Rationa
le), 
, . (
ANSI X3.1591989, 
.)
ANSI
ISO/IEC 9899:1990, ( 24 
ANSI 57 ISO), 
.
?
ANSI X3.159 ISO 9899. 
:
American National Standards Institute
11 W. 42nd St., 13th floor
New York, NY 10036 USA
(+1) 212 642 4900

Global Engineering Documents


2805 McGaw Avenue
Irvine, CA 92714 USA
(+1) 714 261 1455
(800) 854 7179 (U.S. & Canada)

:
ISO Sales

282


Case Postale 56
CH 1211 Geneve 20

Switzerland
C C,
, ANSI C ?
?
, protoize unprotoize 
, 
, , . (
ANSI C).
FSF GNU 
, gcc, gcc.
unproto , 

ANSI C .
GNU GhostScript ansi2knr.
, 
lint. 3 CPROTO
comp.sources.misc 1992 . ,
ctxtract.
:
ANSI C? 
.
ANSIC #,
,
,

:
#define str(x) #x
#define xstr(x) str(x)
#define OP plus
char *opname = xstr(OP);
opname plus, OP.

##, (
) .

283

,
,
: const int n = 5; int a[n];
const . ,
const, ,
, 
. ,
. ( 
++). ,
, 
#define.
char const *p char * const p?
char const *p (
); char * const p
( ) char. .
char ** ,
const char **?
 , 
const, (
), ,
, .
(..
(const char **)) ,
, .
ANSI ,
: extern int func(float); int func(x) float x; {...
extern int func(float); 
int func(x) float x;.
, , ,
. ( ANSI 
) 
.
float double, 
int. (
,
, .)

:

284

int func(float x) { ... }


,
:
extern int func(double);
( 
, ,
, double.)
, char, short int, float
.

?
, 
. , , 
, 
.
extern f(struct x {int s;} *p);
struct x introduced in prototype scope (
)?

, ,
, . 
,
(
). , 
:
struct x;

x.
.
,
#ifdef
ANSI C, , #if, #ifdef
#ifndef .
, 
( , 
).
. 
, 

285

286


/* */.

, 3.1.2 X3.159 
.

main void,
main return no value? ( exit(), main
)
. main int 
, ( ).
exit(), ,
return, , 
, notreached.

memcpy memmove?
memmove ,
. memcpy ,
, . 
memmove.

void 
; , 
/, , 
( main ).
exit(status)
return?
, , 
, , ,
main(), (
setbuf() atexit()),
main().
ANSI
(
) ?
,
ANSI, . 
, , ,
.
, . 
,
, , .
, 
, ,
. ( 
, 
.

, 
,

,

, ANSI

.

ANSIC, ANSI ?
, ,
ANSI , ANSI
.
Frobozz Magic C, ,
ANSIC, ? ,
ANSI,
gcc
( gcc ) 
. , 
? 
.
, .

void *?
,
void *. 
(char *) ,
.
a[3]="abc"? ?
ANSI C (, , 
), . 
, 'a', 'b' 'c'
'\0'. , ,
strcpy, printf %s ..

287

#pragma ?
#pragma ,
:
, , 
( /* NOTREACHED */ lint)
..
#pragma once?

, , 
, .. 
. 
, #ifndef.
,
(unspecified) (undefined)
. ?
,
. 
,
. 
, .
; 
( ) 
.
, 
,
.
?
.

,
.
, 
. 
a^=b^=a^=b.
(
), , 
, typeof.

288


, , , , 
.
,
#define Paste(a, b) a/**/b,

, , , , 
( ,
), 
, 
(Reiser). ANSI, K&R, 
, .
,
ANSI ##, 
:
#define Paste(a, b) a##b
cpp ,
?
, ,
. ,
, ,
.
, 
,
(,  , 
) , if,
if/else else.
:
#define Func() do { \
/* */ \
1; \
2; \
/* ... */ \
} while(0) /* ( ; ) */
, 

. ( 
0, lint .)

289

, ,
, ,
, , 
. 
).
#include
?
, . 
, #include :
Indian Hill Style Guide
; ; 
#include ,
;
Make. ,

( #include ,
; 
#include,
); , grep ( tags)
, ,
, :
#ifndef HEADERUSED
#define HEADERUSED
... ...
#endif
, 
; 
Make ( 
)
#include.
sizeof
#if?
. , 
.
, <limits.h>, ANSI,
. (
,
).

290

#if ,
: ?
, . ( 
).
, ?
, .

, ,
cpp
cpp .
cpp  , 
. 
make(1), .
 , 
, ( m4).
, , ,
#ifdef. ,
,
cpp, #include
#define?
unifdef, rmifdef scpp, 
, .
?
, 
. 
, , ,

strings(1) Unix. ,
(, unix) 
( ) 
.
cpp ?
: ,

:
#define DEBUG(args) (printf("DEBUG: "), printf args)
if(n != 0) DEBUG(("n is %d\n", n));

291

,
.
(DEBUG1, DEBUG2, ..) 
, :
#define DEBUG(args) (printf("DEBUG: "), printf(args))
#define _ ,
DEBUG("i = %d" _ i)
, 

.
?
<stdarg.h> (, ,
<varargs.h>).
, 
, malloc 
.
#include <stdlib.h> /* malloc, NULL, size_t */
#include <stdarg.h> /* va_ */
#include <string.h> /* strcat .. */
char *vstrcat(char *first, ...)
{
size_t len = 0;
char *retbuf;
va_list argp;
char *p;
if(first == NULL)
return NULL;
len = strlen(first);
va_start(argp, first);
while((p = va_arg(argp, char *)) != NULL)
len += strlen(p);
va_end(argp);
retbuf = malloc(len + 1);
/* +1 \0 */
if(retbuf == NULL)
return NULL; /* */
(void)strcpy(retbuf, first);
va_start(argp, first);
while((p = va_arg(argp, char *)) != NULL)
(void)strcat(retbuf, p);
va_end(argp);

292


return retbuf;
}
:

char *str = vstrcat("Hello, ", "world!", (char *)NULL);



. ( , 
).
ANSI, 
("char *vstrcat(first) char
*first; {") <stdio.h> <stdlib.h>, "extern char *mal
loc();", int size_t. , 
(void) varargs.h stdarg.
, 
. , 
.
,
.
, , printf,
,
printf?
vprintf, vfprintf vsprintf.
error, error:
.
#include <stdio.h>
#include <stdarg.h>
void
error(char *fmt, ...)
{
va_list argp;
fprintf(stderr, "error: ");
va_start(argp, fmt);
vfprintf(stderr, fmt,
argp);
va_end(argp);
fprintf(stderr, "\n");
}
<varargs.h>
<stdarg.h>, :
void error(va_alist)

293

va_dcl
{
char *fmt;
va_start:
va_start(argp);

fmt = va_arg(argp, char *);
va_start vfprintf. , va_dcl
.
, ?
. 
nargs(), 
, 
,
. ( 
).

. printf
(%d ..)
( 
). 
( 0, 1,
, ).
, va_arg
CC
, 
va_arg, ,
. , , typedef
, .
,
?
.
, va_list,
vfprintf .
(a 
va_list), 
( ,
va_list),

294

. , 
.
,
?
, .
, ,
, ...
?
?
true false #define enum?
,
,
.
( int ,
char ).
#define enum ,
, , .
:
#define TRUE 1 #define YES 1
#define FALSE 0 #define NO 0
enum bool {false, true}; enum bool {no, yes};

1 0. (, enum 
,
enum).
:
#define TRUE (1==1)
#define FALSE
(!TRUE)
:
#define Istrue(e) ((e) != 0)
, .
TRUE 1,
?

, 1?
(!),
, ,

295

.
, , 0 1.
,
if((a == b) == TRUE)
, , , 
TRUE 1. , TRUE
FALSE ,
( isupper, isalpha ..), 
, 1. ( ,
, if((a == b) == TRUE) if(a == b),
:

296

, ,
, K&R I C
,
K&R I , 
;
,
K&R I.

, ,
ANSI C, 
.

if(((a == b) == TRUE) == TRUE)


,
TRUE FALSE ( )

, .

?
, ,
,
. ( 
).

TRUE FALSE
, ,
.

,

.
, 
, 
ANSI.

enum
#define?
. , ,
, ANSI , 

. ( 
,
.)
,
,
, ,

. ( , 

.

, ).
, 
( ).

,
. ? struct list { char *item; struct list
*next; } /* main */ main(argc, argv) ...
 , main
. ( main 
, ).
, , 
main() , 
( ) .
?

.

( , 
). 

.

297

,
. C++ ==,
.
/ / ?

fwrite:
fwrite((char *)&somestruct, sizeof(somestruct), 1, fp);
fread .
, 
. ,
fopen b.
, :
struct name { int namelen; char name[1]; };
, name
. /?
,
. ANSI ,

,
. , ,

. (,
, ).
. 

...
char name[MAXSIZE];
...
MAXSIZE , , 
name[]. ( , 
).
?
, offsetof, 
ANSI. , 
( 100% ) :
#define offsetof(type, mem) ((size_t) \
((char *)&((type *) 0) >mem (char *)((type *) 0)))

298


.

?
, offsetof().
b a :
offsetb = offsetof(struct a, b)
structp , b
int, , b
:
*(int *)((char *)structp + offsetb) = value;
sizeof ,
, ?
( , 
.
,
/
.
C ?
, , , (,
#pragma), , 
.
?
ANSI 
.

( ,
 ).
,
?

, .
?
, ( 32767
32767), long. , 
( ), short. 

299

int.
/ , 
unsigned. ( 
signed unsigned ). 
float double.
char unsigned char 
, , 
 
.
, , , 
.
,
( 
), 
typedef.
64C 64C
?
64
long int 64 . , ,
sizeof(int) ==
sizeof(long) == 32 , 64 long long ( __lon
glong).
, , 
, , 64
typedef.
,
,
64 ( , 
), 64 .
.
: typedef struct { char *item; NODEPTR next; } *NODEPTR;
.
?
, , .
, NODEPTR
, next. 
, (struct node). 
next struct node *next;, / typedef
.

300

struct node
{
char *item;
struct node *next;
};
typedef struct node *NODEPTR;

.
, , 
typedef 
.
N ,
char?
:
1.
char *(*(*a[N])())();
2. , typedef:
typedef char *pc; /* char */
typedef pc fpc(); /* , char */
typedef fpc *pfpc; /* .. . */
typedef pfpc fpfpc(); /* , ... */
typedef fpfpc *pfpfpc; /* ... */
pfpfpc a[N]; /* ... */
3. cdecl, 
.
cdecl> declare a as array of pointer to function returning
pointer to function returning pointer to char
char *(*(*a[])())()
cdecl , 
, , ,
, ,
. cdecl comp.sources.unix K&R II.

301

,
. ,

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

302


, .
,
, , c 
#define
.
extern ?
extern
,
, , . :
extern int f();


, C

, , 
( ),
int.
, 
. , 
.

?
, (
) ( ) 
, ( ), . (
,
, , , 
).  ( 
). c ,
.h, #include. ,
,
, 
.

ANSI C. , 
UNIX
, 
.

int f();
.
, , , ,
?
:
extern int func();
int (*fp)() = func;
, 
( , "(" ), 
, , (.. 
).
, 
(
 , "(" ).
,
. ?


* 
.
int r, func(), (*fp)() = func;
r = (*fp)();
, 
,
( , )

303

304

 . , 
pcc ANSI, , 
:

, 
, ( fgets); feof() 
.

r = fp();
, , fp 
. ( ;
 ,
, .)

gets()?

, , gets() 
.

* ( ,
).

errno ENOTTY
printf()?
/ 
,
. , ,
(c ENOTTY), 
. , errno
ENOTTY.

auto?
, .
: char c; while((c = getchar())!= EOF)...
, ,
getchar , int. getchar 
, EOF. , 
getchar char,
EOF, EOF (
unsigned char) , 
.
'%' printf?
\%,
%%.
scanf("%d",i)?
scanf ,
, scanf("%d", &i);
double d; scanf("%f", &d);
scanf %lf
double %f float. (
printf, 
%f float, double).
while(!feof(infp)) { fgets(buf, MAXLINE,
infp); fputs(buf, outfp); } ?
. EOF 
, .

,
,
(pipe)
fflush(stdout),
, . 
fflush, , ,
, stdout .
scanf ,
,
scanf , 
.
, \n
, scanf . 
, scanf 
(.. , , , 
, ).
, scanf ,
.  
fgets, sscanf
, ,
. sscanf, 
, 
.

305

, fopen
r+, ,
,
fseek .
, ; ,
fseek fflush
/ +. , 
.
, , ,
, ?
fflush(stdin)?
fflush .
flush () (
), 
fflush. 
, stdio.
, , 
, ,
.
stdin stdout ?
freopen.
freopen, stdout (stdin)?
stdin (stdout) ,
freopen.
,
, stdout
(stdin) .
?
, , . 
UNIX, , (
, , ),
, (pipe)
. , 
. 
(,
, fopen).

306

strncpy C
'\0'?
strncpy 
, 
'\0'. , , strncpy 
, '\0'
.
qsort,
strcmp,
, , ,
char. , 
qsort ,
char. (, strcmp 
char).

const void * char *. ,
, .. (char **)
*; strcmp ,
. :
int pstrcmp(p1, p2) /* , */
char *p1, *p2; /* const void * ANSI C */
{
return strcmp(*(char **)p1, *(char **)p2);
}
qsort.
, ,
,
.
,
?

,
(const void * char *).
:
int mystructcmp(p1, p2)
char *p1, *p2; /* const void * ANSI C */
{
struct mystruct *sp1 = (struct mystruct *)p1;
struct mystruct *sp2 = (struct mystruct *)p2;
/* sp1 > sp2 > ... */

307

}
, , 
:
sp1 = *(struct mystruct **)p1
(,
atoi)? itoa?
sprintf. (
. , sprintf ,

, . sprintf ).
?
time, ctime, / localtime. (
, ANSI).
:
#include <stdio.h>
#include <time.h>
main()
{
time_t now = time((time_t *)NULL);
printf("It's %.24s.\n", ctime(&now));
return 0;
}
, localtime
time_t tm, ctime
time_t .
tm
time_t?
ANSI mktime, 
tm time_t. 
mktime,
.
time_t  
, 
.
strptime;
partime
RCS, , .

308

n ? ?
ANSI/ISO mktime difftime
. mktime() 
, .. tm, 
tm_mday, mktime(), 
year, month day ( time_t).
difftime()
time_t. mktime()
time_t . (, , 
,
time_t; ,  
86400 .).

rand().
,
.
?
:
rand() % N
N, , , ,
.
:
(int)((double)rand() / ((double)RAND_MAX + 1) * N)
,
:
rand() / (RAND_MAX / N + 1)
RAND_MAX ( ANSI,
RAND_MAX <stdlib.h>. , N 
RAND_MAX.
rand()

srand()
. srand() 
, , (

).

309

,
true/false. rand() % 2,
: 0,1,0,1,0...
(, 
, ) ,
. .

,

( ) 
, .
C ,
, Cl,


, ,
, , 
. , 
, , ; 
. (,
UNIX l 
).
,

regesp ( UNIX
) regexp (Henry Spencer).

(C argc argv main)?
strtok,
, 
(, ).
, .
?
lint (, a, c, 
h, p). 
, ,
.

310

warning: possible pointer alignment


problem (:
), lint
malloc?
, lint , 
, malloc
, 
. malloc #define 
#ifdef lint, ,
#define
. , 
, ,
grep v.
ANSIC lint?
, FlexeLint ( 
,
) 
:
Gimpel Software
3207 Hogarth Lane
Collegeville, PA 19426 USA
(+1) 610 584 4261
gimpel@netaxs.com
Lint System V release 4 ANSI
( C ) UNIX Support Labs
System V.
ANSI LINT (
) LCLint 
: ftp: larch.lcs.mit.edu://pub/Larch/lclint/.
, lint .

, lint.
if(!strcmp(s1, s2))
?
, 
.
,
, .

311

, 
:
#define Streq(s1, s2) (strcmp((s1), (s2)) == 0)
, ,
. ,
, .
?
, . , 
( 
).

, ;

.
,

, <math.h> 
, double.
, ,
, ,
.
,
.
,
,
. ( 
.)

312

?
. 
, <math.h>, 
pow(),
.
?
:
(int)(x + 0.5)
.
IEEE NaN
?

IEEE
(, isnan()) ,
Numerical C Extensions Group (NCEG) 
. , 
NaN :
#define isnan(x) ((x) != (x))
IEEE 
.
Turbo C.
, floating point formats not linked
, Turbo C (
PDP11), 
, , .

,
.
, ; 

.

printf scanf, 
%e, %f %g. , 
Turbo C,
, 
, , 
,
.

C ,
, <math.h>,
: undefined: _sin
, , 
. , 
UNIX lm .

,
?
,
( , )
. ,
, , 

313

.
curses cbreak(), , .

, getpass(). UNIX 
ioctl (CBREAK
RAW ; ICANON, c_cc[VMIN] _[VTIME]
System V Posix). MSDOS getch(). 
VMS (SMG$) curses,
$QIO IO$_READ
VBLK (, , IO$M_NOECHO)
. . ,

,
.
, ,
comp.lang.c. FAQ
comp.unix.questions comp.os.msdos.programmer.
,
.
, , , 
, .
( ,
?) , ,
, ?

.
curses nodelay().

/ select ioctl FIONREAD,
kbhit(), rdchk(), O_NDELAY open() fcntl().
?
?
( ). 
termcap curses,  
, .

314

,
?
argv[0] , 
.
argv[0] , , 
,
.
, , .

?
, . 
UNIX /.
, ,
.
UNIX
( setenv() / putenv())

.
, ?

UNIX
access(),  . (
access() , , 
setuid). (
, ) stat(), .
,
.
?
, 
, , , . 
Unix stat ,
,
. c fseek
, ftell, ( 
Unix,
ANSI ).
filesize file
length.

315

, ?

. , , 
?
?
BSD ftruncate(),
chsize(), (, 
) fcntl F_FREESP. MSDOS 
write(fd, "", 0). ,
.

, ?
, , . Unix V7
ftime() c
, System V Posix. 
: nap(), setitimer(), msleep(), usleep(), clock() gettimeofday().
select() poll() ( ) 
. MSDOS

.

?
/ . 
malloc ,
, 
.
BSD Unix system() ld A 
. () SunOS System V
ldl,
. GNU , dld.
?
system().
, ?
Unix
popen(), stdio , 
, ,
( ).
, .

316

(COM) ?
. Unix
, 

. MSDOS 
BIOSa, ( )

.

, ?
,

?
(
, sttic) 
( ) , 
=0. ,
( ), ,
0.0,
.
(..
static), ,
. 
.
, malloc realloc 
, 
, . ,
calloc, , 
.
, : f() { char a[]
= "Hello, world!"; }
, ANSI
(
).
, 
, strcpy,
f(). ( 
char * .)