You are on page 1of 282

,

C++

8

10

10

11

11

11

12

13

15
C++

17
C
17
1
C++
18
1.1
18
1.1.1
18
1.1.2
19
1.1.3
20
1.2
21
1.3
21
1.3.1 T
21
1.3.2
23
1.4
23
1.4.1
23
1.4.2
24
1.4.3
24
1.4.4
24
1.4.5 if
25
1.4.6 switch
25
1.4.7 while
26
1.4.8 for
26
1.4.9
27
1.5
27
1.6
28
1.7
30
1.8
31
1.9
32
1.10
33
1.11
34
1.12 Inline-
35
1.13
36
1.14
37
1.15 (friend)
39
1.16
40
1.17
40
1.18
42
2

15


2.1
2.1.1
2.1.2 (Lvalue)

43
43
44
46

2.1.3
46
2.2
47
2.3
47
2.3.1
48
2.3.2
49
2.3.3
50
2.3.4 void
51
2.3.5
51
2.3.6
52
2.3.7
54
2.3.8
55
2.3.9
57
2.3.10
58
2.3.11
60
2.4
61
2.4.1
61
2.4.2
62
2.4.3
62
2.4.4
63
2.4.5
64
2.4.6 Const
64
2.4.7
65
2.5
66
2.5.1
66
2.5.2
67
2.6
69
3

71
3.1
71
3.1.1
71
3.1.2
76
3.1.3
78
3.1.4
80
3.1.5
81
3.1.6
82
3.2
83
3.2.1
85
3.2.2
85
3.2.2 *
86
3.2.4
87
3.2.5
88
3.2.6
89
3.3
92
3.3.1
93
3.3.2 Goto
95
3.4
96
3.5
97
4


100
4.1
100
4.2
101
4.3
102
4.3.1
104
4.3.2
107
4.3.3
109
4.4
110
4.5
111
4.6
112
4.6.1
112
4.6.2
112
4.6.3
113
4.6.4
114
4.6.5
115
4.6.6
116
4.6.7
117
4.6.8
119
4.6.9
120
4.7
124
4.8
125
5

128
5.1
128
5.2
129
5.2.1
129
5.2.2
130
5.2.3
131
5.2.4
132
5.2.5
134
5.2.6 Inline
135
5.3
135
5.3.1
136
5.3.2
139
5.4
142
5.4.1
142
5.4.2 *
144
5.4.3
144
5.4.4
145
5.4.5
146
5.4.6
147
5.5
149
5.5.1
150
5.5.2
150
5.5.3
152
5.5.4
152
5.5.5
154
5.5.6
155
5.5.7
156
5.5.8
157
5.6
158
6

160

6.1
160
6.2
161
6.2.1
161
6.2.2
162
6.2.3 162
6.3
163
6.3.1
164
6.3.2
164
6.3.3
166
6.4
167
6.5
167
6.6
168
6.7
170
6.8
172
6.9
173
6.10
177
6.11
177
6.12
178
7

181
7.1
181
7.2
182
7.2.1
182
7.2.2
183
7.2.3
184
7.2.4
186
7.2.5
187
7.2.6
187
7.2.7
188
7.2.8
190
7.3
192
7.3.1
192
7.3.2
193
7.3.3
194
7.3.4
196
7.3.5
197
7.3.6
199
7.4
199
7.5
201
7.6
201
7.6.1
201
7.6.2
203
7.6.3
207
7.7
209
7.8
210
8

212
8.1
212
8.2
213
8.2.1
213
8.2.2 , 214
8.2.3
214
8.2.4
216

1.
2.

3.
4.

5.
6.

7.

8.2.5
218
8.3
219
8.3.1
219
8.3.2
220
8.3.3
220
8.3.4
221
8.4
221
8.4.1
221
8.4.2
223
8.4.3 ,
224
8.4.4
225
8.5
226
8.6
226
8.7
228
8.8
228

230

230
2.1
230
2.2 ()
230
2.3
230
2.4
231
2.4.1
231
2.4.2
231
2.4.3
231
2.4.4
232
2.4.5
232
2.4.6
232
2.5
232
2.6
232

233

233
4.1
234
4.2
234
4.3
234
4.4
235
4.5
236
4.4
236
LVALUE()
237

237
6.1
237
6.2 Float double
237
6.3
237
6.4
238
6.5 Unsigned
238
6.6
238
6.7
239
6.8
239

239
7.1
240
7.2
241
7.2.1
242
7.2.2 Sizeof
242
7.2.3
243

7.2.4
243
7.3
244
7.4
244
7.5
245
7.6
245
7.7
246
7.8
246
7.9
246
7.10
246
7.11
246
7.12
246
7.13
247
7.14
247
7.15
247
7.16
248
7.16.1
248
7.16.2
248
7.16.3
248
8.
249
8.1
249
8.2
250
8.3
251
8.4
252
8.4.1
254
8.5
256
8.5.1
257
8.5.2
257
8.5.3
259
8.5.4
259
8.5.5
260
8.5.6
261
8.5.7
261
8.5.8
261
8.5.9 (friends)
262
8.5.10
263
8.5.11
263
8.5.12
263
8.5.13
263
8.5.14
264
8.6
264
8.6.1
265
8.6.2
266
8.6.3
266
8.6.4
267
8.7
267
8.8 typedef
268
8.9
269
8.10
270
8.11 Asm
270
9.
271
9.1
271
9.2 ,
271
9.3
271

9.4 while
271
9.5 do
272
9.6 for
272
9.7 switch
273
9.8 break
273
9.9 continue
274
9.10 return
274
9.11 goto
274
9.12
274
9.13
274
9.14 delete
275
9.15 asm
275
10.
275
10.1
275
10.2
276
11.
276
12.
276
12.1
277
12.2
277
12.3
277
12.4
278
13.
278
14.
278
14.1
278
14.2
278
14.3 ,
279
14.4
279
15.
280
16.
281
17.
281
18.
282
18.1
282
18.2
283
18.3
285
18.4
286
18.5
286
19. " C"
286
19.1
286


, .
..
C++ - , ,

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

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

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

. C++,
.

C++ ,

- 9 . , , , ,
, , , , ,
,
.
/.
, C++ ,
,
, , .
: ,
, , , , ,
.

, ,
, , , , ,
C++, Bell
Labs, , , 26-27 1985 .
,


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

1 - C++,
, .
C
; , C C++.
C++;
,
2, 3 4.
2, 3 4 C++,
: ,
C++ . ,
C++, C.
,
.
5, 6 7 C++
, , C. 5
, ,
, ,
, , . 6 ,

, ,
, ,
,
. 7
,
,

,
.
8 ostream istream,

-.
: ,
C++.
, , C++.
#2.3.4 (
2 3.4). - ; ,
#.8.5.5.
- 11
C++
#.
,
UNIX AT&T 3B, DEC VAX, IBM 370 Motorolla
68000. , ,
, 3B
UNIX System V 2 [15], VAX11/750 8- UNIX
[16] CCI Power 6/32 BSD4.2 UNIX [17]. ,
, - " C++",
"" (
#.15.3), C C++.

.
-. ,

.
, .
, (*1)
, (*2) ,
(*3) - . , ,
, ,
. (*1) ,
, ,
. , ,
, (*5)
. 2-4
C. . [1]

.
5-7. , ,
, .
C++
.

; ,

, .
C;

C.
C++
. , ,
.
,
____________________
# C++ AT&T, Software Sales and Marketing, PO Box
25000, Greensboro, NC 27420, USA ( 800-828-UNIX)
, UNIX. (.
)
- 12 . , ,
C++, - - .
, ,
,
.
,
. , ,
""
, ; ,
16- , 32 .
C++
, C
UNIX.
,
, C++.
C++ .
C++ ,
. , ,

.
C++

.
.

,
.

, C++ C [7]. C
, C
,
. C, ,
BCPL [9]; , //
() C++ BCPL. BCPL,
, C++ - VALOF .
Simula67 [2,3];
(
). ,

.
C++ ,
, 68 [14].
C++ - ( 1983).
1980
"C ".
, , ,
Simula67,
. "C "
,
, ()
. "C "
, , .
C++
- 13 1983; C++
.
C++ .
C. "++" -
C. C+
; ,
. C , C++ , ++C.
D , C

. C++
[8].
C++ ,
, C
.

. C++ ;
, .
, C++ C++.
" C++" " C++".
C++
, ,
.
C++ C, (1)
, ; (2)
; (3)
; (4) UNIX. C
,
, C . , C
"C " (, )
C
Simula- .
C++ , , ,
C,
, ,
C. ,
C (., ,

[12]). , (1)
C, C++ ,
C C++; (2)
,
C, C++ ,
C++ C
C; (3) , C,
, ,
C++, ; (4),
C++ C
, ,
, .
C++,
, , C C++,
.
C ,
C++ (. [11]).
ANSI C [10] ,
"C ".
; , void* ANSI C
- 14 C++. ANSI
, C++,
. , ,
(#.11), , ,
.
, C ANSI C ,
C++ (. #.11).

C++ C
C . , C
C++, ,
,
,
: , .
new delete, C++

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

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

, ,
.
,
,
.
,
. ,
,
, ,
..,
.
, C++ ,
,
C. ( 1000 )
,
. .
10 000 ,
, ,
. C++ ,
,

25 000 .
, , , , ,
,
. ,
- 15 ,
, ,
,
.
, ,
, ,
.. C++ ,
,
, .
,
.

, , ..
,
, , . ,

,
, .
- ,

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


:
,
, , ,
, . ,
" ",

. C.
, "
",
.
, C C++.
, /,
,
, .

. ,
.
;
, . ,

, ,
..
.

. , C++
.
- 16 C++

: ,
, ,
.

-
.
,

.
, , .
- ; ,
: , ,
.
;
( ) .
,
. ,
:
? /

? ?
, -,
, "",
,
" " .
,
: , ,
.. ,
, ,
. C++ ,
, .
,
.
,
, ,
. , ,
() . , A B.
"A B", "A B"
"A B" ,
"A B" (
-). , ,
, "A B
...".
,
, ,

. C++
.
(?). ,
,
.
( )
(#7.2.8).
, ,
- 17 (
).
, .
,
,
; , "A B
C ...". C++ ,
,
(#7.2.5).

;
.
, ,
.
C++
friend (#5.4.1).

( ),
, , , , .
- , .
,
, ,
,
. , ,
,
.
" C++"
" ?" :
", " ".
." C++
, - .
(*)
,
C++. ,
,
.
, .
. ,
.
; !
[1]
,
.
,
:
[a] "" ,
.
____________________
(*) , "." (. .)
- 18 [b] "" ,
.
[c] ,
.
; ()
, .
[2]
,
,
, ,
, :
[a] .

[b] ( ).
[c] -.
[d] , [a], [b]
[c].
[e] -
.
[f] " ";
.
[g] inline-,
.
C
- C,
C++ C, , ,
C++. , , " C"
(#.15). ,
C++ - , C. (#define)
C++ ;
, const (#2.4.6) enum
(#2.4.7), inline (#1.12) -
.
- .
,
, ,
, - ,
. malloc() - new (#3.2.6)
. -
(#2.5.2).
1
C++

- .
-

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

C++.

C++, ,
. ,
,
.
,

. ,
, .
1.1.1
, ,
:
#include
main()
{
cout << "Hello, world\n";
}
#include ,
,
stream.h. cout << "Hello, world\n"
. << (" "*)
( , "Hello, world\n"
____________________
* C <<
. << ; <<
,
. , #1.8. (. )
- 20 cout). -
, .
\, ,
; , \n
. Hello, world
.

main() { ... }
, main.
main,
.
1.1.2
cout ,
<<? C++
;

, ,
.
, , .
,
, ( cout
<<). ,
(
, ).
cout << stream.h, ,
,
.
cout <<. ,
,
stream.h,
, ,
.
C++ CC.
, cc C;
. , "Hello,
world"

- 21 hello.c,
($ - ):
$ CC hello.c
$ a.out
Hello,world
$
a.out -
. ,
-o:
$ CC hello.c -o hello
$ hello
Hello,world
$
1.1.3
( )
. , ,
.
#include
main()
{
int inch = 0;
// inch -
cout << "inches";
cin >> inch;

cout
cout
cout
cout

<<
<<
<<
<<

inch;
" in = ";
inch*2.54;
" cm\n";

}
main() inch.
>> (" ")
cin. cin >>, ,
.
:
$ a.out
inches=12
12 in = 30.48 cm
$
;
. <<
,
:
cout << inch << " in = " << inch*2.54 << " cm\n";
- 22
.
, ,
-. ,
C++, ""
-
#include. , C++
, ,
-;
, ,
<< >>.
1.2
,

. C++
.
/* , */.

(, ).
,
, /* */ .
// ,
, . ,
.
. // ,

/* */, /*
//.
1.3
, ,
. ,
int inch;
, inch int, , inch
.
- , .
.
. , +, -,
* /. , stream.h, int
<<, ostream.
,
, . ,
cout << inch << " in = " << inch*2.54 << " cm\n";
.
, inch
inch*2.54

.
- 23 C++
. C++
, .
1.3.1 T
,
, :
char short int long float double
,
- .
char ,
(, ), int ,
(, ).
, ,
. C++
char, char .
:
1 = sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long)
sizeof(float) <= sizeof(double)

, -
. , ,
, .
const.
, , ,
, const
.
const float pi = 3.14;
const char plus = '+';
, ,
. , ,
, ; , ,

.
.
, .
.

:
+
*
/

(, )
(, )
()
()

:
- 24 == ()
!= ( )
< ()
> ()
<= ( )
>= ( )
, : 7/2 3.
% : 7%2 1.
C++
,
:
double d = 1;
int i = 1;
d = d + i;
i = d + i;
1.3.2
, :

*

*const
&

[]
*
()
,
:
char* p
//
char *const q //
char v[10]
// 10
,
v :v[0] ... v[9]. #1.5,
#1.9.
:
char c;
// ...
p = &c; // p c
& .
1.4
C++ ,

____________________
* . (,
), , ""
. (. .)
- 25 .
,
, .. ,
,
.
1.4.1
C++ ,
, ( ) . ,
~ ()
& ()
^ ( )
| ( )
<< ( )
>> ( )
,

.
; &
, & - .
: +
a+b ,
float, , int. #1.8 ,
,
, ,
.
C++ =, ,
. ,
; , x=sqrt(a=3*x).
. a=b=c c b,
a. ,
. ,
x[i+3]*=4 x[i+3]=x[i+3]*4, ,
x[i+3] .

. .
C++ .
* * , .. *p ,
p.
. , char* p, *p ,
p.
++ --. , p
v, p++ p
.
1.4.2
- .
, . :
____________________
* . dereference - ,
. (. .)
- 26 a = b*3+c;
cout << "go go go";
lseek(fd,0,2);
1.4.3
:
;
. ,
, .
1.4.4

- ,
:
{ a=b+2; b++; }
.
, , .

.
1.4.5 if

; ,
, i c
:
- 27 #include
main()
{
const float fac = 2.54;
float x, in, cm;
char ch = 0;
cout << " : ";
cin >> x >> ch;
if (ch == 'i') {
// inch -
in = x;
cm = x*fac;
}
else if (ch == 'c') // cm -
in = x/fac;
cm = x;
}
else
in = cm = 0;
cout << in << " in = " << cm << " cm\n";
}
, if
.
1.4.6 switch
switch
. :
switch (ch) {

case 'i':
in = x;
cm = x*fac;
break;
case 'c':
in = x/fac;
cm = x;
break;
default:
in = cm = 0;
break;
}
break switch.
case ,
,
default.
default.
- 28 1.4.7 while
, p
q .
0.
while (p != 0) {
*q = *p;
//
q = q+1;
p = p+1;
}
*q = 0;
// 0
while
. , ,
.
, .
. ++
, :
while (*p) *q++ = *p++;
*q = 0;
*p++ : " ,
p, p."
, p
. ,
:
while (*q++ = *p++) ;
, p, p ,

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

*.
1.4.8 for
:
for (int i=0; i<10; i++) q[i]=p[i];

int i = 0;
while (i<10) {
q[i] = p[i];
i++;
}
____________________
* expression-oriented (expression -
). (. .)
- 29 , ,
, . ++
.
for ,
. :
for (i=0; i<10; i++) q[i]=p[i];
, i
.
1.4.9
- , .
.
, ,
()
. :
for (int i = 1; i
1.5
- ,
,
. , 2:
extern float pow(float, int); //pow()

main()
{
for (int i=0; i<10; i++) cout << pow(2,i) << "\n";
}
- , , pow - ,
float int float.
,
.

,
.
. , pow(12.3,"abcd")
, "abcd" ,
int. pow(2,i) 2 float,
. pow
:
- 30 float pow(float x, int n)
{
if (n < 0) error(", pow()");
switch (n) {
case 0: return 1;
case 1: return x;
default: return x*pow(x,n-1);
}
}
,
( )
( ).
return.
, ,
,
.
,
. , ,

:
overload pow;
int pow(int, int);
double pow(double, double);
//...
x=pow(2,10);
y=pow(2.0,10.0);

overload pow;
, pow
.
,
void:
void swap(int* p, int* q)
{
int t = *p;
*p = *q;
*q = t;
}

//

1.6
C++
, , ,
.
,
. :
- 31 extern double sqrt(double);
extern instream cin;
,
( ) , ,
, ,
. , sqrt
math.h,
4, :
#include
//...
x = sqrt(4);

, , .
, inline-
(#1.12)
(#1.3.1). ,
.
.
include ,
, ,
( /usr/include/CC); ,
- ,
. :
#include "math1.h"

#include "/usr/bs/math2.h"
math1.h , math2.h
/usr/bs.
,
,
. header.h :
// header.h
extern char* prog_name;
extern void f();
main.c :
// main.c
#include "header.h"
char* prog_name = ", ";
main()
{
f();
}
f.c :
- 32 // f.c
#include
#include "header.h"
void f()
{
cout << prog_name << "\n";
}
:
$ CC main.c f.c -o silly
$ silly
,
$
1.7
,
ostream. , ,
streambuf. streambuf
, ostream.
, , ostream
;
,

.
, ( C++
class, .. ), ,
,
. :
(private) , ,
, (public) ,
:
class ostream {
streambuf* buf;
int state;
public:
void put(char*);
void put(long);
void put(double);
}
public :
put().
public ostream; buf
state put(),
.
class , ,
ostream, ( ,
int):
ostream my_out;
- 33 , my_out
(, #1.10), :
my_out.put("Hello, world\n");

. my_out
put().
:
void ostream::put(char* p)
{
while (*p) buf.sputc(*p++);
}
sputc() - , streambuf.
ostream , put() ostream'
put().
.
,
ostream::put(): buf
buf , .


this. X this X*
( X) ,
. ostream::put()
:
void ostream::put(char* p)
{
while (*p) this->buf.sputc(*p++);
}
-> ,
.
1.8
ostream <<,
.
, .
@, @ - C++,

operator@, .
:
- 34 class ostream {
//...
ostream operator<<(char*);
};
ostream ostream::operator<<(char* p)
{
while (*p) buf.sputc(*p++);
return *this;
}
<< ostream, s<
");
,
, :
&s1 == &my_out
,
, , (
):
ostream& operator<<(ostream& s, complex z) {
return s << "(" << z.real << "," << z.imag << ")";
}

, ,
s,
, .
, , ,
- ,
,
.
,

. ,
.
class istream {
//...
int state;
public:
istream& operator>>(char&);
istream& operator>>(char*);
istream& operator>>(int&);
istream& operator>>(long&);
//...
};
, long int ,
. ,
, int long
(#.6.6),

.
- 36 1.10
ostream .
,
.
, ,
:
class ostream {
//...
ostream(streambuf*);
ostream(int size, char* s);
};
.
streambuf ,
.
.
, , :
ostream my_out(&some_stream_buffer);

char xx[256];
ostream xx_stream(256,xx);
my_out
- ,
ostream::ostream(streambuf*),
&some_stream_buffer,
streambuf.
,
, .
,
, .
, ,
,
.
1.11
C++ ,

. (
)
. , ,
, ,
..
: " ."
, . ,
C++,
, ,
, ,
, .
- 37 class vector {
int* v;
int sz;
public:
vector(int);
//
~vector();
//
int size() { return sz; }
void set_size(int);
int& operator[](int);
int& elem(int i) { return v[i]; }
};
size ,
0 ... size()-1. set_size
, elem
, operator[]
.
,
, ,


new:
vector::vector(int s)
{
if (s<=0) error(" ");
sz = s;
v = new int[s];
}
vector
, , :
vector v1(100);
vector v2(nelem*2-4);

int& vector::operator[](int i)
{
if(i<0 || sz<=i) error(" ");
return v[i];
}
|| () - .
, ,
.
, []
:
v1[x] = v2[y];
~vector - ,
, , ,
. C
~C.
- 38 vector::~vector()
{
delete v;
}
, delete, ,
, vector
,
.
1.12 Inline-
,
.


( ,
), C++
, .
.

inline-. ,

. . , , size elem
inline-,
vector s(100);
//...
i = s.size();
x = elem(i-1);
,
//...
i = 100;
x = s.v[i-1];
C++ ,
,
. ,
,
.
, , inline, inline, ,
, ,
size() elem().
inline-
. , inline , ,
, . inline
, .
- 39 1.13
,
.
class vec: public vector {
int low, high;
public:
vec(int,int);
int& elem(int);
int& operator[](int);
};

vec
:public vector
, , vec vector. , vec
() vector ,
. , vector
vec, vec ,
vector.
vec vector ,
,
, ,
elem(int) operator[](int). elem()
vec elem() vector:
int& vec::elem(int i)
{
return vector::elem(i-low);
}
:: ,
vec::elem()
. ::
. vec::elem() inline, ,
, , ,
,
v vector.

.
:
vec::vec(int lb, int hb) : (hb-lb+1)
{
if (hb-lb<0) hb = lb;
low = lb;
high = hb;
}
: (hb-lb+1)
vector::vector().
vec::vec(). ,
,
vector:
- 40 #include
void error(char* p)
{
cerr << p << "n\"; // cerr -

exit(1);

}
void vector::set_size(int) { /* */ }
int& vec::operator[](int i)
{
if (i
1.14
- :
- 41 class Vec : public vector {
public:
Vec(int s) : (s) {}
Vec(Vec&);
~Vec() {}
void operator=(Vec&);
void operator*=(Vec&);
void operator*=(int);
//...
};

, Vec::Vec(),
vector::vector() .
. ,
:
void Vec::operator=(Vec& a)
{
int s = size();
if (s!=a.size()) error(" =");
for (int i = 0; i
void error(char* p) {
cerr << p << "\n";
exit(1);
}
void vector::set_size(int) { /*...*/ }
int& vec::operator[](int i) { /*...*/ }
main()
{
Vec a(10);
Vec b(10);
for (int i=0; i
1.15 (friend)
operator+()

. , ,
.
.
, " "
vector::elem(), i
.
, ,

. ,
friend. ,
class Vec; // Vec -
class vector {
friend Vec operator+(Vec, Vec);
//...
};
- 43
Vec operator+(Vec a, Vec b)
{
int s = a.size();
if (s != b.size()) error(" +");
Vec& sum = *new Vec(s);
int* sp = sum.v;
int* ap = a.v;
int* bp = b.v;
while (s--) *sp++ = *ap++ + *bp++;
return sum;
}
friend ,
.
, vector matrix,
(. #.8.8).
1.16
" ," - , - " ,
matrix, ."
, C++
. , .
, .
(#4.7),
. , vector -
, .
:
#include

declare(vector,int);
main()
{
vector(int) vv(10);
vv[2] = 3;
vv[10] = 4; // :
}
vector.h

,
declare(vector,int)
vector, , ,
implement(vector,int)
. implement(vector,int)
,
, declare(vector,int)
,
.
- 44 declare(vector,char);
//...
implement(vector,char);
" ".
#7.3.5.
1.17
-
:
class common {
//...
};
class vector {
common** v;
//...
public:
cvector(int);
common*& elem(int);
common*& operator[](int);
//...
};
, ,
, ""
.
, , , , ..
,
,

cvector
common . :
class apple : public common { /*...*/ }
class orange : public common { /*...*/ }
class apple_vector : public cvector {
public:
cvector fruitbowl(100);
//...
apple aa;
orange oo;
//...
fruitbowl[0] = &aa;
fruitbowl[1] = &oo;
}
, , ,
. ,
, common, apple
orange?
, .
-
, ,
- 45 .
. , ,

apple:
class apple_vector : public cvector {
public:
apple*& elem(int i)
{ return (apple*&) cvector::elem(i); }
//...
};

(),
common*& ( common),
cvector::elem, apple*&.
.
( ,
; .
#7.3.5), ,
.
, , vector(type),
(
implement()) . ,
,
, -
-.

1.18
,
. shape,
- :
class shape {
point center;
color col;
//...
public:
void move(point to) { center=to; draw(); }
point where() { return center; }
virual void draw();
virtual void rotate(int);
//...
};
,
(, move where, , "" ""),
. virual,
, .
:
- 46 class circle: public shape {
int radius;
public:
void draw();
void rotatte(int i) {}
//...
};
, shape_vec - , :
for (int i = 0; i
2

.
- ..
(char, int, float ..)
(, ,
..). ,
, , .
, , ,
. C++,
.

.

C++. ,
,
4, 5 6 .
2.1
() C++
, . ,
, ,
. , :
char ch;
int count = 1;
char* name = "Bjarne";
struct complex { float re, im; };
complex cvar;
extern complex sqrt(complex);
extern int error_number;
typedef complex point;
float real(complex* p) { return p->re; };
const double pi = 3.1415926535897932385;
struct user;
,
.
;
, . ch, count cvar
,
- . real
. constant pi
3.1415926535897932385. complex
. point complex, point
complex.
extern complex sqrt(complex);
extern int error_number;
struct user;
- 48 . , ,
, - .
() sqrt ,
error_number int
, - user
, . C++
,
,
, ,
:
int count;

int count;
// :
exnern int error_number;
exnern int error_number; // :
- ( extern . #4.2):
exnern int error_number;
exnern int error_number;
"" ,
:
struct complex { float re, im; };
typedef complex point;
float real(complex* p) { return p->re };
const double pi = 3.1415926535897932385;
, "" ;

:
int count = 1;
char* name = "Bjarne";
//...
count = 2;
name = "Marian";

char ch;
. , ,
.
2.1.1
; ,
. ,
( ),
,
;
( )
,
. ()
. ,
- 49 .
. :
int x;
f() {

// x

int x;
// x x
x = 1;
// x
{
int x; // x
x = 2; // x
}
x = 3;
// x
}
int* p = &x;

// x

.
, ,
, ,
, , .
.
i x .
::
. :
int x;
f()
{
int x = 1;
::x = 2;

// x
// x

}
.
.
,
. :
int x;
f()
{
int x = x;

//

}
, ,
, x "used before set" (" ,
"), . , ,
::,
. :
- 50 int x;
f()
{

//
int y = x; // x

int x = 22;
y = x;
// x
}
y x, 11,
x, 22.

,
f(int x)
{
int x;
}

//

, x
.
2.1.2 (Lvalue)
, ,

(, *p[a+10]=7). ,
" ".
C++:" ; lvalue
, "(#.5). "lvalue"
",
".
; ,
(. #2.4).
2.1.3
, ,
, ,
,
() ""
. ,
static, . *:
____________________
* #include
. ,
, . (. )
- 51 int a = 1;
void f()
{
int b = 1;
// f()
static int c = 1; //
cout << " a = " << a++

<< " b = " << b++


<< " c = " << c++ << "\n";
}
main()
{
while (a < 4) f();
}

a=1b=1c=1
a=2b=1c=2
a=3b=1c=3
(static)
.
new delete
, ; .
#3.2.4.
2.2
() .
. _
. C++ ,

( , ), , ,
.
,
; (,
$) .
C++ (. #.2.3). :
hello this_is_a_most_unusially_long_name
DEFINED foO bAr
u_name HorseSense
var0
var1 CLASS _class ___
,
:
012
a fool $sys
class 3var
pay.due foo~bar .name if
,
Count count - , ,
, . ,
,
- 52 ,
.


, , var10 - ,
var, 10; elseif - ,
else, if.
2.3
() C++
. ,
( , ),
. :
int error number;
float real(complex* p);
error_number int, ,
..
real complex .
. , int complex,
.
.
- sizeof ( ,
) new (
). :
main()
{
int* p = new int;
cout << "sizeof(int) = " << sizeof(int) "\n";
}

, :
float f;
char* p;
//...
long ll = long(p);
// p long
int i = int(f);
// f int
2.3.1
C++ ,

:
char
short int
int
long int
- 53 -

,
float
double
,
unsigned
unsigned
unsigned
unsigned

char
short int
int
long int

, ,
.. int
, ; , long
long int, unsigned unsigned int. ,
, int. :
const a = 1;
static x;
int.
char
; 8- .
C++ char,
sizeof(char)==1. char
. unsigned char,
, ,
, -
char .
, ,
,
,
.

,
. , ,
.
.
, :
1==sizeof(char)<=sizeof(short)<= sizeof(int)<=sizeof(long)
sizeof(float)<=sizeof(double)
, char
0...127 (
), short int
16 , int , ,
long 24 . -
,
.
#.2.6.
(unsigned)
, .
unsigned int ,

,
. ,
,
- 54 unsigned, - .
:
unsigned surprise = -1;
( ).
2.3.2

. , , ,
. #.6.6.
,
.
, ,
. , ,

8- :
int i1 = 256+255;
char ch = i1
// ch == 255
int i2 = ch;
// i2 == ?
ch=i1 ( !), ch
"-" (.. 8 );
i2 511!
i2? DEC VAX, char ,
-1; AT&T 3B-20, char , 255. C++
(.. )
,
, .
2.3.3
( ,
) :
*
&
[]
()

. :
int* a;
float v[10];
char* p[20];

// 20

void f(int);
struct str { short length; char* p; };

#.8.3-4. ,
. :
- 55 int v[10];
i = v[3];
int* p;
i = *p;

//
//
//
//


, * & , [] () ,
,
, . ,
[] , *,
int* v[10];
int (*p)[10];

//
//

,
.
, ,
, .
.
, . ,
:
int x, y;

// int x; int y;

,
(
). :
int* p, y;
// int* p; int y; int* y;
int x, *p;
// int x; int* p;
int v[10], *p; // int v[10]; int* p;
,
, .
2.3.4 void
void () .
,
void . ,
, ,
.

void f()
// f
void* pv; //
void* .
,
void* ,
void* . ,
,
, .
,
- 56 .
, ,
. :
void* allocate(int size);
void deallocate(void*);

//
//

f() {
int* pi = (int*)allocate(10*sizeof(int));
char* pc = (char*)allocate(10);
//...
deallocate(pi);
deallocate(pc);
}
2.3.5
T T* T.
, T* T.
, ,
:
int* pi;
char** cpp;
// char
int (*vp)[10];
// 10 int'
int (*fp)(char, char*); //
// (char, char*)
// int
- ,
, .
. -
* (). :
char c1 = 'a';
char* p = &c1; // p c1
char c2 = *p; // c2 = 'a'
, p,- c1, ,
c1, 'a', c2 *p

'a'.

. , , ,
( 0):
int strlen(char* p)
{
int i = 0;
while (*p++) i++;
return i;
}
,
, :
- 57 int strlen(char* p)
{
char* q = p;
while (*q++) ;
return q-p-1;
}
;
#4.6.7.
2.3.6
T T[size] " size
T". () 0 size-1. :
float v[3]; // float: v[0], v[1], v[2]
int a[2][5]; // int
char* vpc; // 32

:
extern int strlen(char*);
char alpha[] = "abcdefghijklmnoprstuvwxyz";
main()
{
int sz = strlen(alpha);
for (int i=0; i. strlen()
alpha;
alpha (#2.4.4).
ASCII, :
'a' = 97 = 0141 = 0x61

'b' = 98 = 0142 = 0x62


'c' = 99 = 0143 = 0x63
...
- 58 , alpha ;
,
.
- ,
.
. :
char v[9];
v = "";

//

, .
,
. .
. :
int v1[] = { 1, 2, 3, 4 };
int v2[] = { 'a', 'b', 'c', 'd' };
char v3[] = { 1, 2, 3, 4 };
char v4[] = { 'a', 'b', 'c', 'd' };
, v4 - ( ) ;
,
.
.
,
,
, , (,)
(. #3.2.2). , ,
:
int bad[5,2];

//

:
int v[5][2];
int bad = v[4,1];
//
int good = v[4][1]; //

char v[2][5];
,
char[5].
, -
.

- 59 char v[2][5] = {
'a', 'b', 'c', 'd', 'e',
'0', '1', '2', '3', '4'
}
main() {
for (int i = 0; i<2; i++) {
for (int j = 0; j<5; j++)
cout << "v[" << i << "][" << j
<< "]=" << chr(v[i][j]) << " ";
cout << "\n";
}
}

v[0][0]=a v[0][1]=b v[0][2]=c v[0][3]=d v[0][4]=e
v[1][0]=0 v[1][1]=1 v[1][2]=2 v[1][3]=3 v[1][4]=4
2.3.7
C++ .
,
:
char alpha[] = "abcdefghijklmnopqrstuvwxyz";
char* p = alpha;
char ch;
while (ch = *p++)
cout << chr(ch) << " = " << ch
<< " = 0" << oct(ch) << "\n";
p
char* p = &alpha[0];
,

; ,
extern int strlen(char*);
char v[] = "Annemarie";
char* p = v;
strlen(p);
strlen(v);
strlen .
, ;
, v

(#4.6.3).
+, -,
++ -- , .
p T* ,
- 60 , p T;
p+1 , p-1 -
. , p+1 sizeof(T)
p. ,
main()
{
char cv[10];
int iv[10];
char* pc = cv;
int* pi = iv;
cout << "char* " << long(pc+1)-long(pc) << "\n";
cout << "int* " << long(ic+1)-long(ic) << "\n";
}

char* 1
int* 4
,
.
long
(#3.2.5). long, "" int,
, int (
, sizeof(int)
2.3.8
; struct
() . :
- 61 struct address {
//
char* name;
// "Jim Dandy"
long number;
// 61
char* street;
// "South Street"
char* town;
// "New Providence"
char* state[2];
// 'N' 'J'
int zip;
// 7974
}
, address ( ),
, , -

( , address
,

). ;
C++,
,
.
address ,
,
. (). :
address jd;
jd.name = "Jim Dandy";
jd.number = 61;
, ,
. :
address jd = {
"Jim Dandy",
61, "South Street",
"New Providence", {'N','J'}, 7974
};
(#5.2.4). ,
jd.state "NJ".
'\0', "NJ" ,
, jd.state.

->. :
void print_addr(address* p)
{
cout << p->name << "\n"
<< p->number << " " << p->street << "\n"
<< p->town << "\n"
<< chr(p->state[0]) << chr(p->state[1])
<< " " << p->zip << "\n";
}
,
. :
- 62 address current;
address set_current(address next)
{
address prev = current;
current = next;
return prev;
}

, (== !=)
. ; .
6.

. ,
,
(
: )
,
. "" . ,
( ) sizeof(address) 24, 22,
.
, ,
, ,
. :
struct link{
link* previous;
link* successor;
}
,
,
struct no_good {
no_good member;
};
( no_good).
( )
, .
:
struct list;

//

struct link {
link* pre;
link* suc;
link* member_of;
};
struct list {
link* head;
}
list link
.
- 63 2.3.9

. :
struct s1 { int a; };
struct s2 { int a; };
,
s1 x;
s2 y = x;

// :

,
s1 x;
int i = x;

// :

,
. typedef
, . :
typedef char* Pchar;
Pchar p1, p2;
char* p3 = p1;
.
2.3.10
.
,
; 6.
. x&
x. :
int i = 1;
int& r = i; // r i int
int x = r
// x = 1
r = 2;
// i = 2;
( -,
). ,
.
, .
,
int ii = 0;
int& rr = ii;
rr++;
// ii 1
, rr++ ; ++
int, ii. ,
;
, ()

- 64 . ,
rr, &rr.

, .
,
lvalue (, , .
#.5). &T
lvalue, T. :
[1] -, ,
(#.6.6-8,#.8.5.6);
[2] ;

[3] ,
.

double& dr = 1;
:
double* drp; // ,
double temp;
temp = double(1);
drp = &temp;
, ,
, .
int x = 1;
void incr(int& aa) { aa++; }
incr(x)
// x = 2
,
, aa incr
x. , ,
,
.
:
int x = 1;
int next(int p) { return p+1; }
x = next(x);
// x = 2
void inc(int* p) { (*p)++; }
inc(&x);
// x = 3
,
, .
,

.

.
:
- 65 struct pair {
char* name;
int val;
};
,
. find(),
, pair
, .
(
) :
const large = 1024;
static pair vec[large+1};
pair* find(char* p)
/*
"pair":
p, , "pair",
"pair"
*/
{
for (int i=0; vec[i].name; i++)
if (strcmp(p,vec[i].name)==0) return &vec[i];
if (i == large) return &vec[large-1];
return &vec[i];
}
value(),
, (
):
int& value(char* p)
{
pair* res = find(p);
if (res->name == 0) {
// :
res->name = new char[strlen(p)+1]; //
strcpy(res->name,p);
res->val = 0;
// 0
}
return res->val;
}
value()
( );

. , , :
- 66 const MAX = 256;

//

main()
//
{
char buf[MAX];
while (cin>>buf) value(buf)++;
for (int i=0; vec[i].name; i++)
cout << vec[i].name << ": " << vec [i].val << "\n";
}

cin buf (. 8),
find(). , ,
,
. ,
aa bb bb aa aa bb aa aa
:
aa: 5
bb: 3


(#6.7) [].
2.3.11
()
, .

, ,
. ,
.
register. :
register int i;
register point cursor;
register char* p;
register ,
.
register
(
).

, register,
.
- 67 2.4
C++ :
, . ,
(0)
, char[].
. ,
. C++ : (1)

, const; (2)
;
(3) .
2.4.1
: ,
, .
, :
0

1234

976

12345678901234567890

int, ,
int, long.
,
.
, x (0x),
( 16), ,

,
( 8).
:
0

02

077

0123

- 0, 2, 63, 83.
:
0x0

0x2

0x3f

0x53

a, b, c, d, e f, ,
10, 11. 12, 13, 14 15,
.
;
. ,
, int
, 0xffff
-1;
, 65535.

2.4.2
double.
,
- 68 , , .
:
1.23

.23

0.23

1.

1.0

1.2e10

1.23e-15

,
. , 65.43 e-21
,
():
65.43

21

.
float,
(#2.4.6):
const float pi = 3.14159265;
2.4.3
C++ , ,
,
. - ,
; , 'a' '0'.


, (
,
, ). ,
, ASCII,
'0' 48, EBCDIC,
240.
.
, \
escape-:
'\b'
'\f'
'\n'
'\r'
'\t'
'\v'
'\\' ( )
'\''
'\"'

'\0'

null, , 0

.
-, -
( \, ), -,
- (\x,
). :
- 69 '\6'
'\x6'
6
ASCII ack
'\60'
'\x30'
48
ASCII '0'
'\137' '\x05f'
95
ASCII '_'

,
(. ).

.
2.4.4
- ,
:
" "
,
; '\0' 0.
:
sizeof("asdf")==5;
" ",
"asdf" char[5]. "" (
char[1]). , s
strlen(s)==sizeof(s)-1, strlen()
0.

.
escape-
\. , ,
'\n'. :
cout << " \007\n"
7 - ASKII bel ().
"" :
" ,
"
,

; , . :
cout << " \
ok"

ok
, escape ( ),
,
.
- 70 ,
, . ,
"asdf\000hjkl" ,
strcpy() strlen(), "asdf".


.
,
. :
char v1[] = "a\x0fah\0129"; // 'a' '\xfa' 'h' '\12' '9'
char v2[] = "a\xfah\129";
// 'a' '\xfa' 'h' '\12' '9'
char v3[] = "a\xfad\127";
// 'a' '\xfad' '\127'
,
9- .
2.4.5
(0) ,
.
0. . (
) -
.
2.4.6 Const
const ,
, . :
const int model = 145;
const int v[] = { 1, 2, 3, 4 };
,
. - const ,
:
model = 145;

//

model++;

//

, const ,
, ,
. ,
, const:
const char* peek(int i)
{
return private[i];
}
,
- ,
( -).
- 71 ,
, (,
, ). , ,
. ,
( ) ,
.
,
,
.

, .
:
. "" const
, , . :
const char* pc = "asdf"; //
pc[3] = 'a';
//
pc = "ghjk";
// ok
, ,
, const*. :
char *const cp = "asdf"; //
cp[3] = 'a';
// ok
cp = "ghjk";
//
, const.
:
const char *const cpc = "asdf"; // const const
cpc[3] = 'a';
//
cpc = "ghjk";
//
,

, ,
. .
const
, . :
char* strcpy(char* p, const char* q); // q
,
.
,
, .
:
int a = 1;
const c = 2;
const* p1 = &c; // ok
const* p2 = &a; // ok
int* p3 = &c;
//
*p3 = 7;
// c
, , int.
- 72 2.4.7
,
, const. :
enum { ASM, AUTO, BREAK };
, ,
.
0 ,
:
const ASM = 0;
const AUTO = 1;
const BREAK = 2;
. :
enum keyword { ASM, AUTO, BREAK };
int, .
keyword, int,
, ,
. :
keyword key;
switch (key) {
case ASM:

// -
break;
case BREAK:
// -
break;
}
,
keyword .
. :
enum int16 {
sign=0100000,
//
most_significant=040000, //
least_significant=1
//
};
,
.
2.5

, ,
.
, :
- 73 [1] ;
[2]
.
, .
.
, ,
, .
; ,
(#3.2.6)
.
2.5.1
char ,
, /,
, char ,
C++ . , ,
struct.

, . ;
, -
:

struct sreg {
unsigned enable : 1;
unsigned page : 3;
unsigned : 1;
//
unsigned mode : 2;
unsigned : 4:
//
unsigned access : 1;
unsigned length : 1;
unsigned non_resident : 1;
}
0 DEC PDP11/45 (
, ).
:
.
, ,
.
sreg :
sreg* sr0 = (sreg*)0777572;
//...
if (sr->access) {
//
//
sr->access = 0;
}

.
, , ,
, .
, ,
- 74 ! ,
char int , .
-

.
2.5.2
,
,
, :
struct entry {
char* name;
char type;
char* string_value;
int int_value;
};

// type == 's'
// type == 'i'

void print_entry(entry* p)
{
switch p->type {
case 's':
cout << p->string_value;
break;
case 'i':
cout << p->int_value;
break;
default:
cerr << " type\n";
break;
}
}
string_value int_value
, ,
. , ,
union (); , :
struct entry {
char* name;
char type;
union {
char* string_value; // type == 's'
int int_value;
// type == 'i'
};
};
, entry,
, , entry string_value
int_value . ,
,
.
,
,
- 75 , .
,
, -
.
,
(#5.4.6).
" " (
, ,
,
). , "" VAX' int
int*, :
struct fudge {
union {

int i;
int* p;
};
};
fudge a;
a.i = 4096;
int* p = a.p;

//

:
int int* ,
.
,
(#3.2.5).
,
. , , fudge,
0:
fudge.p = 0;
int i = fudge.i;

// i 0

,
. , fudge :
union fudge {
int i;
int* p;
};
() .
; . #5.4.6.
2.6
1. (*1) "Hello, world" (1.1.1).
2. (*1) #2.1 :
,
. ,
, .
3. (*1) : ; 10
; 10 ;
- 76 ; ;
; ;
.
.
4. (*1.5) ,
. sizeof.
5. (*1.5) , 'a'...'z'
'0'...'9' .
. ,

.
6. (*1) ,
0 . : #2.5.2.
7. (*1.5) ,
double.
8. (*2) ,
, : char, short, int, long, float,
double, unsigned, char*, int* void*?
?
, , int* ?
? , ,
int ?
9. (*1)
C++ ?
C++ ?
- ,
?
10. (*2) one :
const one = 1;
one 2. num
:
const num[] = { 1, 2 };
num[1] 2.
11. (*1) , (
). int*.
,
int&.
12. (*1) str :
char str[] = "a short string";
"a short string"?
13. (*1.5)
. . :
,
,
.
14. (*1) typedef : char;
char; ;
char; ; 7
; 7 ;
8 7 .
3

,


-
C++ ,

.
.

.
,
* .
3.1

,
.
. ,

r=2.5
area=pi*r*r
(pi ), :
2.5
19.635
2.5 - , 19.635 -
.
:
(parser'), ,
(). ,
,
,
,
, ,
.
, ,
(200 ),

C++.
____________________
* ,
indentation. . (. .)
- 78 3.1.1
, :

program:
END
expr_list END

// END -

expr_list:
expression PRINT
// PRINT - '\n' ';'
expression PRINT expr_list
expression:
expression + term
expression - term
term
term:
term / primary
term * primary
primary
primary:
NUMBER
// C++
NAME
// C++ '_'
NAME = expression
- primary
( expression )
, .
, .
, *,
/, +, - ( ) =.
.

; .
, C++,
, .
, .
(, END, NUMBER, + -)
get_token(),
expr(), term()
prim(). () ,
;
.

get_token(). get_token()
curr_tok; curr_tok
token_value:
enum token_value {
NAME
NUMBER END
PLUS='+' MINUS='-' MUL='*'
PRINT=';' ASSIGN='=' LP='('
};
token_value curr_tok;

DIV='/'
RP=')'

- 79 ,
get_token(), curr_tok ,
.
()
, ,
.
"" . expr()
; ,
:
double expr()
{
double left = term();

//

for(;;)
// ````
switch(curr_tok) {
case PLUS:
get_token();
// '+'
left += term();
break;
case MINUS:
get_token();
// '-'
left -= term();
break;
default:
return left;
}
}
. ,
,
. ,
2-3+4 (2-3)+4, .
for(;;) -
; ""*.
for; - while(1).
switch ,
+ -, return
default.
+= -=
.
left=left+term() left=left-term(). left+=term() left=term() ,
. @ x@=y
x=x@y , x
.
+

&

<<

>>

+=

-=

*=

/=

%=

&=

|=

^=

<<=

>>=

____________________
* : "for" - "forever" (). (. .)
- 80 , a+ =1
- + =. (%
; &,| ^
, ; << >>
). term() get_token()
expr().
,
4.
,
.
expr(), term(), prim(),
expr(). -
;
double expr();

//

prim() .
term()
:
double term()
{
double left = prim();

//

for(;;)
switch(curr_tok) {
case MUL:
get_token();
// '*'
left *= prim();
break;
case DIV:
get_token();
// '/'
double d = prim();
if (d == 0) return error(" 0");
left /= d;
break;
default:
return left;
}
}
, , ,
, ,
. error(char*)
. d ,
, .

.

/ .
;
, ,
,
- 81 *. , =
, == .
prim, primary,
, , -
, ,
:
double prim()
// primary ()
{
switch (curr_tok) {
case NUMBER:
//
get_token();
return number_value;
case NAME:
if (get_token() == ASSIGN) {
name* n = insert(name_string);
get_token();
n->value = expr();
return n->value;
}
return look(name-string)->value;
case MINUS:
//
get_token();
return -prim();
case LP:
get_token();
double e = expr();
if (curr_tok != RP) return error(" )");
get_token();
return e;
case END:
return 1;
default:
return error(" primary");
}
}
NUMBER ( , ),
. get_token()
number_value.
,
,
. .
: ,

( token_value), (
) .
curr_tok,
NUMBER number_value.
,
.
, NUMBER
number_value, name_string
NAME. , -
____________________
*
. (. )
- 82 , ,
, ,
. .
#3.1.3; ,
:
srtuct name {
char* string;
char* next;
double value;
}
next ,
:
name* look(char*);
name* insert(char*);
name, ; look() ,
. ,
,
.
3.1.2
- .
, ,
,
.
( )
.
,
.
.
get_token(). ,
;
.

,

;
get_token() .
, '\n'
,
. , '\n'
. ,
(, ..):
char ch
do { // '\n'
if(!cin.get(ch)) return curr_tok = END;
} while (ch!='\n' && isspace(ch));
- 83 cin.get(ch)
ch. if(!cin.get(ch)) ,
cin ;
END, .
! (), get()
.
(inline) isspace()
, (#8.4.1); isspace(c)
, c ,
.
, isspace() ,
;
isalpha(), isdigit() isalnum(),
get_token().
, ,
,
. ,
. '\n' ';'
:
switch (ch) {
case ';':
case '\n':
cin >> WS; //
return curr_tok=PRINT;
,
get_token(). WS -
, ;
.
get_token().
, case ()
,
. PRINT
curr_tok.

:
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '.':
cin.putback(ch);
cin >> number_value;
return curr_tok=NUMBER;
case , ,
, ,
.
>>
double,
: ( )
cin, number_value.
, NAME, ,
:
- 84 if (isalpha(ch)) {
char* p = name_string;
*p++ = ch;
while (cin.get(ch) && isalnum(ch)) *p++ = ch;
cin.putback(ch);
*p = 0;
return curr_tok=NAME;
}
name_string , .
isalpha() isalnum() ; isalnum(c)
, c , .
, , :
token_value get_token()
{
char ch;
do { // '\n'
if(!cin.get(ch)) return curr_tok = END;
} while (ch!='\n' && isspace(ch));
switch (ch) {
case ';':
case '\n':
cin >> WS; //
return curr_tok=PRINT;
case '*':
case '/':
case '+':
case '-':
case '(':

case ')':
case '=':
return curr_tok=ch;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '.':
cin.putback(ch);
cin >> number_value;
return curr_tok=NUMBER;
default:
// NAME, NAME=
if (isalpha(ch)) {
char* p = name_string;
*p++ = ch;
while (cin.get(ch) && isalnum(ch)) *p++ = ch;
cin.putback(ch);
*p = 0;
return curr_tok=NAME;
}
error(" ");
return curr_tok=PRINT;
}
}
- 85
token_value ( )
*,
.
3.1.3

name* look(char* p, int ins =0);
,
. =0 ,
, look()
. , look("sqrt2")
look("sqrt2",0), , .
,
:
inline name* insert(char* s) { return look(s,1);}
, :
srtuct name {
char* string;
char* next;
double value;
}

next .
- name:
const TBLSZ = 23;
name* table[TBLSZ];
,
table
.
look()
( -
):
int ii = 0;
//
char* pp = p;
while (*pp) ii = ii<<1 ^ *pp++;
if (ii < 0) ii = -ii;
ii %= TBLSZ;
,
"" ii ("" ). x^y
,
x y .
, ii ,
____________________
* . (. .)
- 86 .
:
ii <<= 1;
ii ^= *pp++;
, ^ , +.
- .
if (ii < 0) ii = -ii;
ii %= TBLSZ;
, ii 0...TBLSZ-1; % -
( ).
:
extern int strlen(const char*);
extern int strcmp(const char*, const char*);
extern int strcpy(const char*, const char*);
name* look(char* p, int ins =0)
{
int ii = 0;
//

char* pp = p;
while (*pp) ii = ii<<1 ^ *pp++;
if (ii < 0) ii = -ii;
ii %= TBLSZ;
for (name* n=table[ii]; n; n=n->next) //
if (strcmp(p,n->string) == 0) return n;
if (ins == 0) error(" ");
name* nn = new name;
//
nn->string = new char[strlen(p)+1];
strcpy(nn->string,p);
nn->value = 1;
nn->next = table[ii];
table[ii] = nn;
return nn;
}
- ii
next. name
strcmp(). ,
name, name.
name
new (. #3.2.6),
, .
,
, ,
.
. strlen() ,
, new - , strcpy() -
.
- 87 3.1.4
,
. ,
:
int no_of_errors;
double error(char* s) {
cerr << "error: " << s << "\n";
no_of_errors++;
return 1;
}
,
,
, ,
.

. get_token()
, error()
, .
, .
,
,
. exit(),
(#8.3.2),
.
- abort(),

- ( );
, , .
3.1.5
,
, .
main() :
int main()
{
// :
insert("pi")->value = 3.1415926535897932385;
insert("e")->value = 2.7182818284590452354;
while (cin) {
get_token();
if (curr_tok == END) break;
if (curr_tok == PRINT) continue;
cout << expr() << "\n";
}
return no_of_errors;
}
- 88 , main()
,
.
,
.
- .
:
cout << expr() << "\n";
cin
, - ,
END , get_token()
. break
switch ( ,

for, while do). PRINT


( , '\n' ';') expr()
. continue
,
while (cin) {
// ...
if (curr_tok == PRINT) continue;
cout << expr() << "\n";
}

while (cin) {
// ...
if (curr_tok == PRINT) goto end_of_loop;
cout << expr() << "\n";
end_of_loop
}
#.9.
3.1.6
, ,
,
,
.
,
.
, main().
, main() :
, argc, ,
argv. - , argv
char*[argc]. (,
) argv[0], argc
. ,
dc 150/1.1934
- 89 :
argc
argv[0]
argv[1]

2
"dc"
"150/1.1934"

;
,
.
, ,
(#8.5). , cin

:
int main(int argc, char* argv[])
{
switch(argc) {
case 1:
//
break;
case 2:
//
cin = *new istream(strlen(argv[1]),argv[1]);
break;
default:
error(" ");
return 1;
}
//
}
,
main()
switch. main() ,
,
, ,
:
dc "rate=1.1934;150/rate;19.75/rate;217/rate"
, ;
UNIX.
3.2
C++ #.7;
, , .
.

. _ - , , - , ,
- , , , lvalue - , .
( *, ()
..) ,
.
- 90 ,
. , a=b=c a=(b=c),
a+b+c (a+b)+c, *p++ *(p++), (*p)++.
( 1)
-------------------------------------------------------------------

::
_ ::
::

::
------------------------------------------------------------------->

->
[]

[ ]
()

(_)
()

(_)
sizeof
sizeof
sizeof
sizeof ( )
------------------------------------------------------------------++

lvalue++
++

++lvalue
-
lvalue--
--lvalue
~

~
!

!

-
+

+
&

& lvalue
*

*
new
()
new
delete ()
delete
delete[]
delete[ ]

()
( )
( )
------------------------------------------------------------------*

*
/

/
%
()
%
------------------------------------------------------------------+
()
+
()
-

. ,
, . : a+b*c a+(b*c),
* , +, a+b-c (a+b)-c,
+ - ( +
).
- 91 ( 2)
------------------------------------------------------------------<<

lvalue <<
>>

lvalue >>
-------------------------------------------------------------------

<

<
<=

<=
>

>
>=

>=
------------------------------------------------------------------==

==
!=

!=
------------------------------------------------------------------&

&
------------------------------------------------------------------^

^
------------------------------------------------------------------|

|
------------------------------------------------------------------&&

&&
------------------------------------------------------------------||

||
------------------------------------------------------------------?:
if
? :
------------------------------------------------------------------=

lvalue =
*=

lvalue =
/=

lvalue /=
%=

lvalue %=
+=

lvalue +=
-=

lvalue -=
<<=

lvalue <<=
>>=

lvalue >>=
&=

lvalue &=
|=

lvalue |=
^=

lvalue ^=
------------------------------------------------------------------,
()
,
- 92 3.2.1
C++ ;
:
,
( ),
, .
, ,

,
" " ( ,
). ,
if (i<=0 || max
3.2.2
.
int i = 1;
v[i] = i++;
- 93 v[1]=1, v[2]=1.

. ,
,
.

,

&&

||

, , .
, b=(a=2,a=1) b 3. #3.3.1
&& ||. , ,
() ,
.
f1(v[i],i++);
f2( (v[i],i++) )

//
//

f1 , v[i] i++,
- . -
- ,
. f2 , ,
i++.
. ,
a*(b/c) (a*b)/c, * /
. ,
, , ,
(t=b/c,a*t).
3.2.2 *
++

. ++lvalue lvalue+=1,
lvalue=lvalue+1 , lvalue
. ,
() , ,
(). , --.
++ -- ,

. ++x ( )
x. , y=++x y=(x+=1). x++,
, x. , y=x++
y=(t=x,x+=1,t), t - , x.

. ,
:
inline void cpy(char* p, const char* q)
{
while (*p++ = *q++) ;
}
____________________
* "" "",
, C,
C. (. .)
- 94 , ,
,
, ; p++
, p . p T*
:
long(p+1) == long(p)+sizeof(T);
3.2.4

&

>>

<<

, char, short, int, long


unsigned , .
( ).
,
. &
, | , ^
.
. ,
( ) :
enum state_value { _good=0, _eof=1, _fail=2, _bad=4};
// , , ,
_good . ,
, , .
:
cout.state = _good;

, ,
:
if (cout.state&(_bad|_fail)) // good
, &
, |.
, , :
cin.state |= _eof;
|= ,
( , state==_bad),
cin.state = _eof;
. :
state_value diff = cin.state^cout.state;
- 95 stream_state ( )
,
. , ,
, , ,
, .
, (#2.5.1)

. , ,
, , 16
32- int :
unsigned short middle(int a) { return (a>>8)&0xffff; }

:
&&

||

0 1,
if, while for (#3.3.1).
, !0 ( ) 1, ~0 (
) -,
-1.
3.2.5

.
. :
float r = float(1);

1
1.0.
lvalue, (
).
:
C (double)a
double(a). ,
. ,

char* p = (char*)0777;
:
typedef char* Pchar;
char* p = Pchar(0777);
,
.
- 96 Pname n2 = Pbase(n1->tp)->b_name;
Pname n3 = ((Pbase)n2->tp)->b_name;

//
//

-> , ,

((Pbase)(n2->tp))->b_name

, .
:
any_type* p = (any_type*)&some_object;
p some_object
any_type.
, .
, ,
, , .
, ,
(,
,
, , struct
; . #2.5.2). ,

,
, .
:

int i = 1;
char* pc = "asdf";
int* pi = &i;
i = (int)pc;
pc = (char*)i; // : pc
//
// sizeof(int)
3.2.6
,
(. #2.1.3).
.

, .
, ,
. ,
,
, . new,
delete. ,
new, ,
.
,
, .
,
.
,
. :
struct enode {
token_value oper;
enode* left;
enode* right;
};
enode* expr()
{
enode* left = term();
for(;;)
switch(curr_tok) {
case PLUS:
case MINUS:
get_token();
enode* n = new enode;
n->oper = curr_tok;
n->left = left;
n->right = term();
left = n;
break;
default:
return left;

}
}
:
- 98 void generate(enode* n)
{
switch (n->oper) {
case PLUS:
//
delete n;
}
}
, new, ,
delete, ,
, new. "
", , ,
new, . delete
, new,
. delete .
new . :
char* save_string(char* p)
{
char* s = new char[strlen(p)+1];
strcpy(s,p);
return s;
}
, ,
new, delete
. :
int main(int argc, char* argv[])
{
if (argc < 2) exit(1);
char* p = save_string(argv[1]);
delete p;
}
, ,
new, , (,
).

delete. :
int main(int argc, char* argv[])
{
if (argc < 2) exit(1);
int size = strlen(argv[1])+1;

char* p = save_string(argv[1]);
delete[size] p;
}

, (#5.5.5).
(#.7.2.3):
void operator new(long);
void operator delete(void*);
- 99 new .
, new ?
,
.
char* p = new char[100000000];
, - . new
, ,
_new_handler ( #4.6.9).
set_new_handler().
:
#include
void out_of_store()
{
cerr << " new : \n";
exit(1);
}
typedef void (*PF)();

//

extern PF set_new_handler(PF);
main()
{
set_new_handler(out_of_store);
char* p = new char[100000000];
cout << ", p = " << long(p) << "\n";
}
, "",

new :
_new_handler - ,
. , new delete,
, , operator new()

operator delete(),
, new.
, , ,
, delete . , , .
new 0,

_new_handler.
include
main()
{
char* p = new char[100000000];
cout << ", p = " << long(p) << "\n";
}
- 100
, p = 0
! , ,
_new_handler,
new ( ,

, ; . #5.5.6).
3.3
C++ #.9,
, , .
.

------------------------------------------------------------------:

{_ opt}
opt
if ( )
if ( ) else
switch ( )
while ( )
do while ()
for ( opt ; opt )
case _ :
default :

break ;
continue ;
return opt ;
goto ;
:
_:

_
, ,
.
.
- 101 3.3.1
if,
switch:
if ( )
if ( ) else
switch ( )
C++ .
==

!=

<

<=

>

>=

1, , 0.
, 1,
0.
if ( )
, ,
( ). ,
. , a
,
if (a) // ...

if (a != 0) // ...

&&

||

. && ||
, . :

if (p && 1count) // ...


, p , ,
1count.
if
if. :
if (a <= d)
max = b;
else
max = a;
:
max = (a<=b) ? b : a;
, ,
, .
switch -
if. :
- 102 switch (val) {
case 1:
f();
break;
case 2;
g();
break;
default:
h();
break;
}
:
if (val == 1)
f();
else if (val == 2)
g();
else
h();
, (switch) ,

( ).
switch .
, switch - ,
, case. :
switch (val) {

//

case 1:
cout << "case 1\n";
case 2;
cout << "case 2\n";
default:
cout << "default: case \n";
}
val==1
case 1
case 2
default: case
.
- break, goto. :
- 103 switch (val) { //
case 0:
cout << "case 0\n";
case1:
case 1:
cout << "case 1\n";
return;
case 2;
cout << "case 2\n";
goto case1;
default:
cout << "default: case \n";
return;
}
val==2
case 2
case 1
, case
goto:
goto case 1;

//

3.3.2 Goto
C++ goto.
goto ;
:
,
, , C++

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

(break

). :
for (int i = 0; i
3.4


.
.
(
, ).
.

,
, ,

[1] ;
[2] ;
[3] .
,
.
, .
- ,
, .
:
// "v" .
// "v" "f()".
// init()
// .
// "cleanup()"
.
// "wierd()".
// "f()" .
C++
. ,
, , (#4.2)
, (.

#5.5.2).
- ,
. :
a = b+c; // a b+c
count++; //
,
, ,
, .
:
- 105 [1] , ,
,
,
..;
[2] ,
, (
) , , -
;
[3] ,
/ ;
[4] .
:
// tbl.c:
/*

. Ralston: "A first course ..." . 411.
*/
// swap() AT&T sB20.
/**************************************
Copyright (c) 1984 AT&T, Inc.
All rights reserved
****************************************/
-
.
, .
,
//,
/* */, .
3.5
1. (*1) for
while:

for (i=0; im
*p.m
*a[i]
7. (*2) : strlen(),
, strcpy(), ,
strcmp(), . ,
,
,
.
8. (*1) , :
a := b+1;
if (a = 3) // ...
if (a&077 == 0) // ...
, ,
.
9. (*2) cat(),
,
. new,
. rev(),
.
, rev(p) p
.
10. (*2) ?
- 107 void send(register* to, register* from, register count)
// .
{
register n=(count+7)/8;
switch (count%8) {
case 0: do { *to++ = *from++;
case 7: do { *to++ = *from++;
case 6: do { *to++ = *from++;
case 5: do { *to++ = *from++;
case 4: do { *to++ = *from++;
case 3: do { *to++ = *from++;
case 2: do { *to++ = *from++;
case 1: do { *to++ = *from++;
while (--n>0);
}
}
- ?
11. (*2) atoi(), ,
, int. ,
atoi("123") - 123. atoi() ,

C++. atoi() ,

.
itoa(),
.
12. (*2) get_token() (#3.1.2),
, ,
.
13. (*2) #3.1
, sqrt(), log() sin(). :

. .
14. (*3)
. :
, ,
.
, . ,
, .
, ,
.
15. (*1.5) ,

name_string number_value
symbol:
struct symbol {
token_value tok;
union {
double number_value;
char* name_string;
};
};
16. (*2.5) ,
C++ . , cin, // /* */
cout.
- 108 ( ,
). .
// /* */ ,
.
17. (*2) - ,
,
.
4

,
.
- .


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

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

expr(), term() prim(). ,
( ,
, ),
. ,
-. ;
" "
, ,
200 ,
.
,
,
, , ,
. , *.
- , .
____________________
* . (. .)
- 110 () . UNIX'
ld. ,
,
.


,
().
,
. , ,
. C++ ,
**.
4.2
, ,
, , ,
, ,
. ,
, , . ,
, :
// file1.c:
int a = 1;
int f() { /* - */ }
// file2.c:
extern int a;
int f();
void g() { a = f(); }
a f(), g() file2.c,- ,
file1.c. extern () ,
a file2.c () ,
. a , extern
,
.
. ,
. :
// file1.c:
int a = 1;
int b = 1;
extern int c;
// file2.c:
int a;
extern double b;
extern int c;
____________________
** C ,
. C, ,
, ,
, . (.
)
- 111 -

: a (int a;
, int a=0;), b
, c , .
( ) ,
. , ,
.
C++ ( C
):
// file1.c:
int a;
int f() { return a; }
// file2.c:
int a;
int g() { return f(); }
-, file2.c C++, f() ,
. -, ( file2.c
) , a
.
, static. :
// file1.c:
static int a = 6;
static int f() { /* ... */ }
// file2.c:
static int a = 7;
static int f() { /* ... */ }
a f static,
. a
f().
static,
( ).
static , ,
,
.
:
// file1.c:
const int a = 6;
inline int f() { /* ... */ }
struct s { int a,b; }
// file1.c:
const int a = 7;
inline int f() { /* ... */ }
struct s { int a,b; }
" " ,

inline- ,
, file1.c file2.c
C++ . ,
? , :
- 112 , .. ,
, , .
( ).
4.3

.
,
- 1950-,
*.
, ,
, , ,
.
,
, ,
, /
.
#include -

() .
#include "to_be_included"
, #include,
"to_be_included". C++,
.
, C ,
CC ,
, ,
.
,
.
,
CC -E file.c
file.c ,
CC .

< >. :
#include
//
#define "myheader.h"
//
<> ,

( ,
/usr/include/CC, usr/include).
, include :
#include < stream.h > //
____________________
* ,
, ,
? (. )
- 113 , ,
- , ,
,
.
,
, ,
,
.
, ,
,
,
#include.
:

struct point { int x, y; }

extern int strlen(const char*);
inline- inline char get() { return *p++; }

extern int a;

const float pi = 3.141593

enum bool { false, true };


include
#include

#define Case break;case

/* */

char get() { return *p++; }

int a;


const tbl[] = { /* ... */ }
UNIX ,
() .h. , ,
.c. ,
, ".h " ".c ". #4.7
. , C++ ,
C, C++ , const
inline
.
,
,

, . ,
,
( ).

.
,
.
4.3.1


, ,
,
- 114 . .c
: lex.c, syn.c, table.c main.c, dc.h,
,
.c :
// dc.h:
enum token_value {
NAME, NUMBER, END,
PLUS='+', MINUS='-', MUL='*',
PRINT=';', ASSIGN='=', LP='(',
};
extern
extern
extern
extern
extern
extern

DIV='/',
RP=')'

int no_of_errors;
double error(char* s);
token_value get_token();
token_value curr_tok;
double number_value;
char name_string[256];

extern double expr();


extern double term();
extern double prim();
struct name {
char* string;
name* next;
double value;
};
extern name* look(char* p, int ins = 0);
inline name* insert(char* s) { return look(s,1); }
, lex.c
:

// lex.c:
#include "dc.h"
#include
token_value curr_tok;
double number_value;
char name_string[256];
token_value get_token() { /* ... */ }
, ,
,
, - ,
. , lex.c
:
extern token_value get_token();
// ...
token_value get_token() { /* ... */ }
- 115 ,
, . ,
get_token() token_value,
int, lex.c .
syn.c :
// syn.c:
#include "dc.h"
double prim() { /* ... */ }
double term() { /* ... */ }
double expr() { /* ... */ }
table.c :
// table.c:
#include "dc.h"
extern char* strcmp(const char*, const char*);
extern char* strcpy(char*, const char*);
extern int strlen(const char*);
const TBLSZ = 23;
name* table[TBLSZ];
name* look(char* p; int ins) { /* ... */ }

, table.c
,
. ,
.c extern.
" ",
, ,
. , ,
strlen() main() ().
,
.
, ,
extern dc.h, .
"" ,
C , ,
, , , ,
, . !
main.c, , :
- 116 // main.c: ,
#include "dc.h"
int no_of_errors;
double error(char* s) { /* ... */ }
extern int strlen(const char*);
main(int argc, char* argv[]) { /* ... */ }
,
.
- (. 5-8).

. ""
.
. ,
.

.
4.3.2

,
. ,
, ,
. . -
, ,
.

.c .h , .c
( , )
.h , , .h ( ,
).
, , error()
,
. ,
error() main():
- 117 // error.h:
extern int no_errors;
extern double error(char* s);
// error.c
#include
#include "error.h"
int no_of_errors;
double error(char* s) { /* ... */ }
.h
.c ,
.h , .c .

. :
// table.h:
struct name {
char* string;
name* next;
double value;
};
extern name* look(char* p, int ins = 0);
inline name* insert(char* s) { return look(s,1); }
// table.c:
#include "error.h"
#include
#include "table.h"
const TBLSZ = 23;
name* table[TBLSZ];
name* look(char* p; int ins) { /* ... */ }

,
.
.
- 118 // lex.h:
enum token_value {
NAME,
NUMBER,
END,
PLUS='+', MINUS='-',
MUL='*', DIV='/',
PRINT=';', ASSIGN='=', LP='(',
RP=')'
};
extern token_value curr_tok;
extern double number_value;
extern char name_string[256];
extern token_value get_token();
.

get_token()
number_value name_string.
// lex.c:
#include
#include
#include "error.h"
#include "lex.h"
token_value curr_tok;
double number_value;
char name_string[256];
token_value get_token() { /* ... */ }
:
// syn.c:
extern double expr();
extern double term();
extern double prim();
// syn.c:
#include "error.h"
#include "lex.h"
#include "syn.h"

double prim() { /* ... */ }


double term() { /* ... */ }
double expr() { /* ... */ }
, , :
- 119 // main.c:
#include
#include
#include
#include
#include
#include

"error.h"
"lex.h"
"syn.h"
"table.h"

main(int argc, char* argv[]) { /* ... */ }


,
. ,
, C++.
, ,
,
. ,
10 50
, 500 ,
,
. :

. ,

(
..),
.
4.3.3

,
. , ,
, .c extern.
, :
// file1.c:
// "extern"
int a = 7;
const c = 8;
void f(long) { /* ... */ }
// file2.c:
// "extern" .c
extern int a;
extern const c;
extern f(int);

int g() { return f(a+c); }


extern file2.c
file1.c,
. ,
,
, .

, ,
- 120 , static, ,
. :
// table.c:
#include "error.h"
#include
#include "table.h"
const TBLSZ = 23;
static name* table[TBLSZ];
name* look(char* p; int ins) { /* ... */ }
, table
look(). "" TBLSZ
.
4.4
.c .h
. .h ,
; .c .
. ,
, .
, - ,
. .
, .c ,
.h .
, ,
.c . ,
, .c ,
.
(.o ).
, ,
.
,
.h , ,
(), .h ,
().
,

, . ,
table , ,
.
5.


,
() .
. , ,
, , / ,
; . #5.5.2.
- 121 4.5
" " " -
" ( , ),
C++ ? , ,
;
, 8- UNIX.
.
.o ,
.c
. .h ,
.o .
, ( )

.
:
extern
extern
extern
extern
extern

double
double
double
double
double

sqrt(double);
sin(double);
cos(double);
exp(double);
log(double);

//

, ,
sqrt.c, sin.c, cos.c, exp.c log.c.
math.h , , :
$ CC -c sqrt.c sin.c cos.c exp.c log.c
$ ar cr math.a sqrt.o sin.o cos.o exp.o log.o
$ ranlib math.a

. ar,
math.a. , , .
runlib, , ,
. , ,
ar.
, , :

$ CC myprog.c math.a
, math.a
.o ? :
$ CC myprog.c sqrt.o sin.o cos.o exp.o log.o
.o ,
, .
, myprog.c sqrt()
cos(), ,
$ CC myprog.c sqrt.o cos.o
, cos.c sin.c.
, CC .a (
, math.a) , ,
- 122 .a , .o
.
,
(
, ,
), , , ,
.
4.6
- C++ -
, .
, .
, .
4.6.1
,
( ) ,
. :
extern
extern
extern
extern

double sqrt(double);
elem* next_elem();
char* strcpy(char* to, const char* from);
void exit(int);

.
,
. ,
,
double sr2 = sqrt(2);

sqrt()
2.0.
.
.
, .
4.6.2
, , -
( ). -
, . :
extern void swap(int*, int*);
void swap(int*, int*)
{
int t = *p;
*p =*q;
*q = t;
}

//

//

- 123 ,
inline (#1.12),
, register (#2.3.11).
,
- .
4.6.3
,
,
.
. ,

,
.
(#4.6.5),
(#4.6.8)
(#4.6.6).
void f(int val, int& ref)
{
val++;
ref++;
}
f(), val++
, ref++
. :
int i = 1;

int j = 1;
f(i,j);
j, i. , i, ,
, j, .
#2.3.10, ,
, ,
( . #6.5 #8.4).
,
. const,
, ,

:
void f(const large& arg)
{
// "arg"
}
, const
, , ,
. :
- 124 extern int strlen(const char*);
//
extern char* strcpy(char* to, const char* from);
extern int strcmp(const char*, const char*);
.
,
. const ,
, (#6.6).
4.6.4
, void, ( )
.
return. :
int fac(int n) {return (n>1) ? n*fac(n-1) : 1; }
return:
int fac(int n)
{
if (n > 1)
return n*fac(n-1);
else
return 1;
}
,

.
.


. :
double f()
{
// ...
return 1;
}

// double(1)

, ,
.
,
.
:
int* f() {
int local = 1;
// ...
return &local;
}

//

,
:
- 125 int& f() {
int local = 1;
// ...
return local;
}

//

, .
:
int& f() { return 1;}

//

4.6.5
,
. :
int strlen(const char*);
void f()
{
char v[] = "a vector"
strlen(v);
strlen("Nicholas");
};

, T[]
T*. ,
,
. ,
, ( )
.
.
, .
, .
,
, ,
, (. #1.11).
:
void compute1(int* vec_ptr, int vec_size);
struct vec {
int* ptr;
int size;
};

//

//

void compute2(vec v);


,
,
. :
- 126 char* day[] = {
"mon", "tue", "wed", "thu", "fri", "sat", "sun"
};
, ,
.
, :
void print_m34(int m[3][4])
{
for (int i = 0; i<3; i++) {
for (int j = 0; j<4; j++)
cout << " " << m[i][j];
cout << "\n";
}
}
, , ,
.

(#2.3.6).
:

void print_mi4(int m[][4], int dim1)


{
for (int i = 0; i
4.6.6
,
. ,
hex(),
.

.
, , ,
.
, ,
.
" , ".
hex(i,0),
:
extern char* hex(long, int =0);
.
, ,
. :
cout << "**" << hex(31) << hex(32,3) << "**";

cout << "**" << hex(31,0) << hex(32,3) << "**";
:
** 1f 20**

.
,
- 128 int f(int, int =0, char* =0); // ok
int g(int =0, int =0, char*); //
int f(int =0, int, char* =0); //
, * =
(*= ):
int nasty(char*=0);

//

4.6.7
, - ,


,
.
(overloading).
C++:
, +,
, .
, , ,
.
,
. :
overload print;
void print(int);
void print(char*);
, ,
, . , -
, , .
, -
.
sqrt, print open.
, +, *
<< (#6.2) (#5.2.4 #6.3.1),
.
f(), , f
.
f.
, ,
:
[1] , ,
;
[2]
;
[3] ,
(#6.3),

, .
:
- 129 overload print(double), print(int);
void f();
{
print(1);
print(1.0);
}
, f 1
1.0 . , char short
int. , float
double.

C++
(#.6.6) .
, , .
int long, int double, long, double
: , void*,

(#7.2.4).
, :
overload print(double), print(long);
void f(int a);
{
print(a);
}
a double, long.
(
print(long(a)) print(double(a))).
,

, ().
:
overload pow;
int pow(int, int);
double pow(double, double);
//
complex pow(double, complex); //
complex pow(complex, int);
complex pow(complex, double);
complex pow(complex, complex);
unsigned const.
4.6.8

, .
(...),
" , - ". :
int printf(char* ...);
- 130 , printf
, char*, , .
:
printf("Hello, world\n");
printf(" %s %s\n", first_name, second_name);
printf("%d + %d = %d\n",2,3,5);

,
.
printf() ,
, printf()
. %s "
char*", %d " int". ,
, ,
. :
printf(" %s %s\n",2);
-
.
, ,
,
. char short
int, float double. ,
.
, wild(...),
,
,
C.
,
. ,
,
,
.
,
.
C ,
, :
extern int fprintf(FILE*, char* ...); //
extern int execl(char* ...);
//
extern int abort(...);
//
,
,
. ,
, ,
. ,

:
- 131 void error(int ...);
main(int argc, char* argv[])
{
switch(argc) {
case 1:
error(0,argv[0],0);

break;
case 2:
error(0,argv[0],argv[1],0);
default:
error(1,argv[0],"",dec(argc-1),"",0);
}
}
:
#include
void error(int n ...)
/*
"n" char*,
*/
{
va_list ap;
va_start(ap,n);
// arg
for (;;) {
char* p = va_arg(ap,char*);
if(p == 0) break;
cerr << p << " ";
}
va_end(ap);

// arg

cerr << "\n";


if (n) exit(n);
}
va_list
va_start(). va_start va_list'
. va_arg
.
; va_arg() ,
,
. ,
va_start(), va_end(). ,
va_start() ,
; va_end() .
4.6.9
:
. , ,
. :
- 132 void error(char* p) { /* ... */ }

void (*efct)(char*);
void f()
{
efct = &error;
(*efct)("error");
}

//

// efct error
// error efct

, , efct,
, *efct.
() ,
*, *efct("error").
*efct("error"), .
(. #7.3.4).
,
, .
.
:
void (*pf)(char*);
void f1(char*);
int f2(char*);
void f3(int*);

// void(char*)
// void(char*)
// int(char*)
// void(int*)

void f()
{
pf = &f1;
pf = &f2;
pf = &f3;

// ok
// :
// :

(*pf)("asdf");
(*pf)(1);

// ok
// :

int i = (*pf)("qwer"); // : void int'


}

.
, -
, --.
:
typedef int (*SIG_TYP)();
//
typedef void (*SIG_ARG_TYP);
SIG_TYP signal(int,SIG_ARG_TYP);
. ,
*
.
, :
____________________
* -
. , . (.

)
- 133 typedef void (*PF)();
PF edit_ops[] = { //
cut, paste, snarf, search
};
PF file_ops[] = { //
open, reshape, close, write
};
, ,
, (button) :
PF* button2 = edit_ops;
PF* button3 = file_ops;

. , - ,
, .
.
()
. ,
3 2, :
(button2[3])();
-
.
,
.
.

, ,
:
- 134 typedef int (*CFT)(char*,char*);
int sort(char* base, unsigned n, int sz, CFT cmp)
/*
"n" "base"

, "cmp".
"sz".
:
*/
{

for (int i=0; iname, Puser(q)->name);


}
int cmp2(char*p, char* q)
// dept
{
return Puser(p)->dept-Puser(q)->dept;
}
:
main ()
{
sort((char*)heads,6,sizeof(user),cmp1);
print_id(heads,6);
//
cout << "\n";
sort((char*)heads,6,sizeof(user),cmp2);
print_id(heads,6);
//
}
inline-, , ,
(#.8.9).
- 136 4.7
* #.11. C , C++
. :
, .
, ,
. , ,
,
C .
:
#define name rest of line
name , rest of line.
:
named = name
:
named = rest of line
. :
#define mac(a,b) argument1: a argument2: b
mac .
mac() a b. :

expanded = mac(foo bar, yuk yuk)



expanded = argument1: foo bar argument2: yuk yuk
C++ ,
C++ - .
,
, .
.
:
#define
#define
#define
#define

Case break;case
nl <<"\n"
forever for(;;)
MIN(a,b) (((a)<(b))?(a):(b))

:
#define PI 3.141593
#define BEGIN {
#define END }
:
____________________
* . (. .)
- 137 #define SQUARE(a) a*a
#define INCR_xx (xx)++
#define DISP = 4
, ,
:
int xx = 0;

//

void f() {
int xx = 0;
//
xx = SQUARE(xx+2);
// xx = xx+2*xx+2
INCR_xx;
// xx
if (a-DISP==b) {
// a-= 4==b
// ...
}
}
,
:: (#2.1.1)
,
(. MIN ).

:
#define m1(a) something(a)
#define m2(a) something(a)

//
/* */

,
int a = m1(1)+2;
int b = m2(1)+2;

int a = something(1)
int b = something(1)

// +2;
/* */+2;

.
, . , C
- .
- , , , ,
, ( .
#7.3.5).
4.8
1. (*1) : ,

; ; ,
; ,
. ,

. : typedef.
2. (*1) ? ?
- 138 typedef int (rifii&) (int, int);
3. (*1.5) "Hello, world",
"Hello,
". ,
hello
.
4. (*1.5) ,
, ,
cout.
, cat
().
5. (*2) C C++.
,
. , ,
#define enum const inline. .c
extern
C++. malloc() free() new

delete. .
6. (*2) sort() (#4.6.7)
.
7. (*2) struct tnode .#8.5.
tnode.
tnode.
tnode
. tnode ,
() ,
new .
tnode.
8. (*2) "", . .h
push(), pop()
(). .c ,
.
9. (*2) ,
. , /usr/include
/usr/include/CC ( ,
). ,
.
10. (*2) .
11. (*2) , cin
cout .
:
c - c^key[i], key () - ,
.
key , .
key
. (
),
.
12. (*3) ,
, , .
: David Kahn: The Code-Breakers, Macmillan, 1967, New
York, pp 207-213.
13. (*3) error,
printf, %s, %c %d,
. printf().
- 139 %s .., #8.2.4.
.
14. (*1) ,
typedef?
15. (*2) - ,
,
. ?
? x
y?
16. (*1) ?
#define PI = 3.141593

#define MAX(a,b) a>b?a:b


#define fac(a) (a)*fac((a)-1)
17. (*3) ,
( C ). cin
cout.
. : (#3.1)
,
.
5

"",
, int float.
-

C++,
. ,
, , , .
,
, (
, "") .
C++
.
5.1
,
, ,
,
. , ,
,
.
().
, C++ float +, -, * ..
,
. ,
,
. ,
, ,
trunk_module ( ), -
list_of_paragraphs ( ). , ,
, ,
, , .
, ,
.
,
.
-

(, ,
) ,
(,
, ).
,

().
:
#5.2 .
, ,
(class).
, .
- 141 .
,
. .
""
.
.
#5.3 .
, ,
.
#5.4 .
, .
,
, .
(friend).
, .
#5.5 .
, .
(
),
.
.
5.2
- .
, ,
, ,
.
5.2.1
struct
, date
:
struct date { int month, day, year; };
// :
, , }
date today;
void set_date(date*, int, int, int);

void next_date(date*);
void print_date(date*);
// ...
.
, :
- 142 struct date {
int month, day, year;
void
void
void
void
};

set(int, int, int);


get(int*, int*, int*);
next();
print();

, ,


. :
date today;
//
date my_burthday; //
void f()
{
my_burthday.set(30,12,1950);
today.set(18,1,1985);
my_burthday.print();
today.next();
}

,
:
void date::next()
{
if ( ++day > 28 ) {
//
}
}

. ,
.
5.2.2
date

date, ,
date.
struct class:
- 143 class date {
int month, day, year;
public:
void set(int, int, int);
void get(int*, int*, int*);
void next();
void print();
};
public . ,
, .
, , .
Struct - class, ,
,
. :
void date::ptinr()
// ,
{
cout << month << "/" << day << "/" year;
}

date. :
void backdate()
{
today.day--;
}

//

,
, . ,
,
(, 36, 1985)
, , ,
, .
, date
. ,
,
.

. ,
, , .
5.2.3
, ,

. :
- 144 class x {
int m;
public:
int readm() { return m; }
};
x aa;
x bb;
void f()
{
int a = aa.readm();
int b = bb.readm();
// ...
}
member() m aa.m, bb.m.
, ,
.
this. x
this
x* this;
, ,
. this ,
. x
:
class x {
int m;
public:
int readm() { return this->m; }
};
this .
this ,
. , :
- 145 class dlink {
dlink* pre; //
dlink* suc; //
public:
void append(dlink*);
// ...

};
void dlink::append(dlink* p)
{
p->suc = suc; // , p->suc = this->suc
p->pre = this; // this
suc->pre = p; // , this->suc->pre = p
suc = p;
// , this->suc = p
}
dlink* list_head;
void f(dlink*a, dlink *b)
{
// ...
list_head->append(a);
list_head->append(b);
}

, 7.
,
this, pre suc (, ).
dlink, dlink::append() .
C++ class, .
5.2.4

set_date() ( )
. ,
, , (
, , )
. :
,
.
, .
, , .
:
class date {
// ...
date(int, int, int);
};
,
. ,
:
- 146 date today = date(23,6,1983);
date xmas(25,12,0);
//

// (xmas - )
date my_burthday;
// ,

. , .
:
class date {
int month, day, year;
public:
// ...
date(int, int, int); //
date(char*);
//
date(int);
// ,
date();
// :
};

, (#4.6.7).
,
:
date
date
date
date

today(4);
july4(" 4, 1983");
guy("5 ");
now;
//

,
overload.
,

overload
.
date .
"",
- ,
- , ,
, .
, ,
.
- .
date ,
" : today" ().
- 147 class date {
int month, day, year;
public:
// ...
date(int d =0, int m =0, int y =0);
date(char*);
//
};

date::date(int d, int m, int y)


{
day = d ? d : today.day;
month = m ? m : today.month;
year = y ? y : today.year;
// ,
// ...
}
, "
",
. day mounth ,
, year . ,
. 1 . ..
(year==-1) 1 . .. (year==1),
.

.
, . :
date d = today;

//

, ,
. X
,
X(X&). #6.6.
5.2.5
, ,
, .
, ,
.
X ~X() (" ").
,
(. #3.2.6),
. , ,
,
:
- 148 class char_stack {
int size;
char* top;
char* s;
public:
char_stack(int sz) { top=s=new char[size=sz]; }
~char_stack()
{ delete s; } //
void push(char c) { *top++ = c; }
char pop()
{ return *--top;}
}

char_stack
:

void f()
{
char_stack s1(100);
char_stack s2(200);
s1.push('a');
s2.push(s1.pop());
char ch = s2.pop();
cout << chr(ch) << "\n";
}
f(), char_stack s1,
100 , s2,
200 . f()
.
5.2.6 Inline

. , ,
-
, . ,
, , .
,
(
) , ,
.
, inline. , ( )
, inline. , ,
, char_stack,
,
! ,
,
. , ,
. ,
.
inline .
:
- 149 char char_stack {
int size;
char* top;
char* s;
public:
char pop();
// ...
};

inline char char_stack::pop()


{
return *--top;
}
5.3
? ,
. ,
" ",
. ,
,
. ,
.
: ,
, , , ..
"",
, .
,
,
. ( , )
.

(. #4.4: ). , ,
. ,
, ,
. . ,
, .
5.3.1

,
.
, 3.
:
struct name {
char* string;
char* next;
double value;
};
table:
- 150 // table.h
class table {
name* tbl;
public:

table() { tbl = 0; }
name* look(char*, int = 0);
name* insert(char* s) { return look(s,1); }
};
, 3 ,
. table,
table .. :
#include "table.h"
table globals;
table keywords;
table* locals;
main() {
locals = new table;
// ...
}
table::look(),
name :
#include
name* table::look(char* p, int ins)
{
for (name* n = tbl; n; n=n->next)
if (strcmp(p,n->string) == 0) return n;
if (ins == 0) error(" ");
name* nn = new name;
nn->string = new char[strlen(p)+1];
strcpy(nn->string,p);
nn->value = 1;
nn->next = tbl;
tbl = nn;
return nn;
}
table, ,
,
. -
, ,
table,
:
- 151 class table {
name** tbl;

int size;
public:
table(int sz = 15);
~table();
name* look(char*, int = 0);
name* insert(char* s) { return look(s,1); }
};
,
,
.
, ,
, .
,
.
-:
table::table(int sz)
{
if (sz < 0) error(" ");
tbl = new name*[size=sz];
for (int i = 0; inext) {
delete n->string;
delete n;
}
delete tbl;
}
name
table::~table().
,
(#3.1.3):
- 152 #include
name* table::look(char* p, int ins)
{
int ii = 0;
char* pp = p;
while (*pp) ii = ii<<1 ^ *pp++;
if (ii < 0) ii = -ii;
ii %= size;
for (name* n=tbl[ii]; n; n=n->next)
if (strcmp(p,n->string) == 0) return n;
if (ins == 0) error(" ");
name* nn = new name;

nn->string = new char[strlen(p)+1];


strcpy(nn->string,p);
nn->value = 1;
nn->next = tbl[ii];
tbl[ii] = nn;
return nn;
}
,
, - .

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

? ,
? ,
,
, ,
, ? - .
,
, , ,
( )
.
,
"" .
, ""
, ,
.
, , ,


. inline-
- 153 , . ,
C C++
( C struct ,
C++ ). C++
.
5.3.2
( )
,

( ).
, .
,
;
. , ,

.
intset,
" ":
class intset {
int cursize, maxsize;
int *x;
public:
intset(int m, int n); // , m int' 1..n
~intset();
int member(int t);
void insert(int t);

// t ?
// "t"

void iterate(int& i)
{ i = 0; }
int ok(int& i)
{ return i
void error(char* s)
{
cerr << "set: " << s << "\n";
exit(1);
}
intset main(),
. ,
. ,
:
- 154 main(int argc, char* argv[])
{
if (argc != 3) error(" ");
int count = 0;
int m = atoi(argv[1]);
//
int n = atoi(argv[2]);
// 1..n
intset s(m,n);
while (count maxsize) error(" ");
int i = cursize-1;
x[i] = t;
while (i>0 && x[i-1]>x[i]) {
int t = x[i];
// x[i] [i-1]
x[i] = x[i-1];
x[i-1] = t;
i--;

}
}
:
int intset::member(int t)
{
int l = 0;
int u = cursize-1;
while (l <= u) {
int m = (l+u)/2;
if (t < x[m])
u = m-1;
else if (t > x[m])
l = m+1;
else
return 1;
}
return 0;

//

//
//

}
, , ,

, intset .
,
( , ,
intset -, ).
: iterate() , ok()
, , next() ,
:
class intset {
// ...
void iterate(int& i)
{ i = 0; }
int ok(int& i)
{ return iiterate(var);
while (set->ok(var)) cout << set->next(var) << "\n";
}
#6.8.
6

!
-
, C++
.
.
, ,

, () [],
.

. , ,

.
6.1
,
. ,
int C++ +, -, *, / ..
()
.
, ,
. ,
.
, , ,
,
C++. C++
,
. ,
,

, ,
. :
class complex {
double re, im;
public:
complex(double r, double i) { re=r; im=i; }
friend complex operator+(complex, complex);
friend complex operator*(complex, complex);
};
,

, +
* ( ). + *
operator+ operator*. ,
, b c complex, b+c ( )
operator+(b,c).
. :
- 177 void f()
{
complex a = complex(1, 3.1);
complex b = complex(1.2, 2);
complex c = b;
a = b+c;
b = b+c*a;

c = a*b+complex(1,2);
}
,
b=b+(c*a), b=(b+c)*a.
6.2
,
:
+ - * / % ^ & | ~ !
= < > += -= *= /= %= ^= &=
|= << >> >>= <<= == != <= >= &&
|| ++ -- [] () new delete
- (#6.7),
(#6.8),
(#3.2.6). ,
. , ,
% !.
, ,
,
. , **, pow().
,
. ,
**, ,
, .
** ( ) (
)? a**p a*(*p)
(a)**(p)?
operator ( ,
), , , operator<<.
,
. -
. :
void f(complex a, complex b)
{
complex c = a + b;
//
complex d = operator+(a,b); //
}
complex
.
- 178 6.2.1
,
, ,
. , @ aa@bb

aa.operator@(bb),
operator@(aa,bb). , aa@bb .
, ,
, ,
, . ,
@ aa@ @aa
aa.operator@(), operator@(aa). ,
, aa@ @aa .
:
class X {
//
friend
friend
friend
friend

X
X
X
X

operator-(X);
//
operator-(X,X); //
operator-();
// :
operator-(X,X,X); // :

// ( : this)
X* operator&(); // & ( )
X operator&(X); // & ( )
X operator&(X,X); // :
};
++ -- ,
.
6.2.2
, ,
. ,
, =
, ,
, lvalue (#.6).


. , a int, ++a a+=1,
a=a+1.
,
, .
, operator+=() complex

complex::operator+()

complex::operator=().
= &
.
"" . , ,
X. , ,
X::operator&(), . -
- 179 -

X,
*. , , X::operator&()
, .
6.2.3
,
(,
new delete, ).
,
,
. , ,
.
,
, . , ,
aa 2: aa+2,
,
aa.operator+(2), 2+aa ,
int, + ,
2.operator+(aa). ,
, 2+aa aa+2,
. +,
, ,
, 2+aa aa+2.
.
.
,

, ,
, (. #4.6.7).
6.3

, -,
. .
:
____________________
* "",
, .
. ( )
- 180 class complex {
double re, im;
public:
complex(double r, double i) { re=r; im=i; }
friend complex operator+(complex, complex);
friend complex operator+(complex, double);
friend complex operator+(double, complex);

friend complex operator-(complex, complex);


friend complex operator-(complex, double);
friend complex operator-(double, complex);
complex operator-()
// friend complex operator*(complex, complex);
friend complex operator*(complex, double);
friend complex operator*(double, complex);
// ...
};
, complex, :
void f()
{
complex a(1,1), b(2,2), c(3,3), d(4,4), e(5,5);
a = -b-c;
b = c*2.0*c;
c = (d+e)*a;
}
complex double,
operator+(), . ,

; ,
, complex, .
6.3.1
()
, double
complex. :
class complex {
// ...
complex(double r) { re=r; im=0; }
};
, ,
:
complex z1 = complex(23);
complex z2 = 23;
z1, z2 complex(23).
- 181 - ,
. ,
, ,

, . , complex
:
class complex {
double re, im;
public:
complex(double r, double i = 0) { re=r; im=i; }
friend complex operator+(complex, complex);
friend complex operator*(complex, complex);
};
, complex
, .
complex . ,
a=b*2 :
a=operator*( b, complex( double(2), double(0) ) )

, .
,
,
, ,
.
6.3.2

, ,
:
[1]
(
);
[2] ,
;
[3] ,
.
,
,
. X::operator T(), T - ,
X T. ,
tiny (),
0...63,
:
- 182 class tiny {
char v;
int assign(int i)
{ return v = (i&~63) ? (error(" "),0) : i; }
public:

tiny(int i)
{ assign(i); }
tiny(tiny& i)
{ v = t.v; }
int operator=(tiny& i) { return v = t.v; }
int operator=(int i) { return assign(i); }
operator int()
{ return v; }
}
, tiny
int, , int. tiny
.
tiny ,
tiny::operator int(), int tiny. ,
, int, tiny,
int. :
void main()
{
tiny c1 = 2;
tiny c2 = 62;
tiny c3 = c2 - c1; // c3 = 60
tiny c4 = c3;
// ()
int i = c1 + c2; // i = 64
c1 = c2 + 2 * c1; // : c1 = 0 ( 66)
c2 = c1 -i;
// : c2 = 0
c3 = c2;
// ()
}
tiny ,
.
, .
-
,
( 100, ,
- ..).
, + *.

, (
) ,
.
istream ostream ,
,
while (cin>>x) cout<>x istream&.
, cin,
while (. #8.4.2).
,
, .
- 183 6.3.3
( ) X

, X,

X.


. ;
, .

. . :
class x { /* ... */ x(int); x(char*); };
class y { /* ... */ y(int); };
class z { /* ... */ z(x); };
overload f;
x f(x);
y f(y);
z g(z);
f(1);
// : f(x(1)) f(y(1))
f(x(1));
f(y(1));
g("asdf");
// : g(z(x("asdf")))
g(z("asdf"));

, . :
class x { /* ... */ x(int); }
overload h(double), h(x);
h(1);
h(double(1)),
h(x(1)), .

, #4.6.7.

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

- 184 ,
complex.

. ,
,
aa=f(1), aa .
aa x, , x,
, - f(x(1)), aa - y,
f(y(1)).
g("asdf"),
g(z(x("asdf"))). ,
,
.
,
,
, ..
, ,
, !
6.4
,
1.2 12e3 double. ,
, ,
.
, .
inline,
. , ,
comlpex,

zz1*3+zz2*comlpex(1,2) , .
*, +
, comlpex(3)
comlpex(1,2), inline.
6.5
comlpex ,
, , ,
.
double , . ,
.
, ,
. :
class matrix {
double m[4][4];
public:
matrix();
friend matrix operator+(matrix&, matrix&);
friend matrix operator*(matrix&, matrix&);
};

,
,
- 185 . ,
.
:
matrix operator+(matrix&, matrix&);
{
matrix sum;
for (int i=0; i<4; i++)
for (int j=0; j<4; j++)
sum.m[i][j] = arg1.m[i][j] + arg2.m[i][j];
return sum;
}
operator+() + ,
.
:
class matrix {
// ...
friend matrix& operator+(matrix&, matrix&);
friend matrix& operator*(matrix&, matrix&);
};
,
.
,
.
,
. , .
(
, ) .
6.6
string:
struct string {
char* p;
int size; // , p
string(int sz) { p = new char[size=sz]; }
~string() { delete p; }
};
- ,
.
. , #5.10,

. :
void f()
{
string s1(10);
string s2(20);
s1 = s2;
}
- 186 , s1=s2
.
f() s1 s2
.
,
string:
struct string {
char* p;
int size; // , p
string(int sz) { p = new char[size=sz]; }
~string() { delete p; }
void operator=(string&)
};
void string::operator=(string& a)
{
if (this == &a) return;
// s=s;
delete p;
p=new char[size=a.size];
strcpy(p,a.p);
}
string ,
. f()
:
void f()
{
string s1(10);
s2 = s1;
}
, .

. string::operator=()
, : p
.
,
. , ,
. , , ,

, :
- 187 struct string {
char* p;
int size; // , p
string(int sz) { p = new char[size=sz]; }
~string() { delete p; }
void operator=(string&)
string(string&);
};
void string::string(string& a)
{
p=new char[size=a.size];
strcpy(p,a.p);
}
X X
X(X&). ,
- .
. X ,
,
,
:
class X {
// ...
X(something); // :
X(&X);
// :
operator=(X&); // :
~X();
// :
};
, :
. ,
. .
,
. X(X&), :
string g(string arg)
{
return arg;
}
main()
{
string s = "asdf";
s = g(s);
}

, g() s "asdf".
s arg :
string(string&).
g() string(string&);
,
- 188 s. , ,
string::~string() .
6.7

operator[]. () operator[]
.
..
#2.3.10,
.
.
:
struct pair {
char* name;
int val;
};
class assoc {
pair* vec;
int max;
int free;
public:
assoc(int);
int& operator[](char*);
void print_all();
};
assoc pair max.
free.
:
assoc::assoc(int s)
{
max = (s<16) ? s : 16;
free = 0;
vec = new pair[max];
}

, #2.3.10. assoc
:

- 189 #include
int assoc::operator[](char* p)
/*
"pair":
p,
"pair"
"pair", p
*/
{
register pair* pp;
for (pp=&vec[free-1]; vec<=pp; pp--)
if (strcmp(p,pp->name)==0) return pp->val;
if (free==max) { // :
pair* nvec = new pair[max*2];
for ( int i=0; iname = new char[strlen(p)+1];
strcpy(pp->name,p);
pp->val = 0;
// : 0
return pp->val;
}
assoc , .
,
, :
vouid assoc::print_all()
{
for (int i = 0; i>buf) vec[buf]++;
vec.print_all();
}
- 190 6.8
, (_),
,
, .
operator()
.

,
,
.
assoc .
, assoc_iterator,
,
assoc. , assoc,
:

class assoc {
friend class assoc_iterator;
pair* vec;
int max;
int free;
public:
assoc(int);
int& operator[](char*);
};

class assoc_iterator{
assoc* cs; // assoc
int i;
//
public:
assoc_iterator(assoc& s) { cs = &s; i = 0; }
pair* operator()()
{ return (ifree)? &cs->vec[i++] : 0; }
};
assoc_iterator assoc,
pair
, ().
0:
main() //
{
const MAX = 256; //
char buf[MAX];
assoc vec(512);
while (cin>>buf) vec[buf]++;
assoc_iterator next(vec);
pair* p;
while ( p = next() )
cout << p->name << ": " << p->val << "\n";
}
- 191
, :
.
,
.
,
.
, first(), next()
last() (, ).
6.9

string.


C++.
#include
#include
class string {
struct srep {
char* s;
int n;
};
srep *p;

//
//

public:
string(char *);
// string x = "abc"
string();
// string x;
string(string &);
// string x = string ...
string& operator=(char *);
string& operator=(string &);
~string();
char& operator[](int i);
friend ostream& operator<<(ostream&, string&);
friend istream& operator>>(istream&, string&);
friend int operator==(string& x, char* s)
{return strcmp(x.p->s, s) == 0; }
friend int operator==(string& x, string& y)
{return strcmp(x.p->s, y.p->s) == 0; }
friend int operator!=(string& x, char* s)
{return strcmp(x.p->s, s) != 0; }
friend int operator!=(string& x, string& y)
{return strcmp(x.p->s, y.p->s) != 0; }
};
( ):
- 192 string::string()
{
p = new srep;
p->s = 0;
p->n = 1;
}
string::string(char* s)

{
p = new srep;
p->s = new char[ strlen(s)+1 ];
strcpy(p->s, s);
p->n = 1;
}
string::string(string& x)
{
x.p->n++;
p = x.p;
}
string::~string()
{
if (--p->n == 0) {
delete p->s;
delete p;
}
}
, .
() :
string& string::operator=(char* s)
{
if (p->n > 1) { //
p-n--;
p = new srep;
}
else if (p->n == 1)
delete p->s;
p->s = new char[ strlen(s)+1 ];
strcpy(p->s, s);
p->n = 1;
return *this;
}
,
:
- 193 string& string::operator=(string& x)
{
x.p->n++;
if (--p->n == 0) {
delete p->s;
delete p;
}
p = x.p;
return *this;

}
,
. (
<<, ):
ostream& operator<<(ostream& s, string& x)
{
return s << x.p->s << " [" << x.p->n << "]\n";
}

(#8.4.1).
istream& operator>>(istream& s, string& x)
{
char buf[256];
s >> buf;
x = buf;
cout << "echo: " << x << "\n";
return s;
}

. :
void error(char* p)
{
cerr << p << "\n";
exit(1);
}
char& string::operator[](int i)
{
if (i<0 || strlen(p->s)s[i];
}

. ,
. ,
done, ,
.
.
- 194 main()
{
string x[100];
int n;
cout << " \n";
for (n = 0; cin>>x[n]; n++) {

string y;
if (n==100) error(" ");
cout << (y = x[n]);
if (y=="done") break;
}
cout << " \n";
for (int i=n-1; 0<=i; i--) cout << x[i];
}
6.10
, , ,
,
- . :
, (.
), .
X:
class X {
// ...
X(int);
int m();
friend int f(X&);
};
f(X&)
X::m() ( ),
X. X::m() "
", f() ,
. :
void g()
{
1.m();
f(1);
}

//
// f(x(1));

, ,
, . ,
lvalue (=, *=, ++
..), .
,
, ,
. ,
,
lvalue (+, -, || ..).
- 195 , ,
,
, , .

. , ,
m m.inv(). , inv()
m,
, m, .
, :
, - -
. ,
.
, ;
. ,
.
,
this. ,
.
6.11
,
,
. ,
,
. , ,
, , +
.
/
,

int, ,
.
.
, .
, C++

, .
6.12
1. (*2) string.
+ " " +=.
string ?
2. (*1.5) ()
.
3. (*3) string ,
.
,
, ,
.
4. (*2) string , ,
.. ,
- 196 , ,

sring.
5. (*3) string
,
. ,
,
.
,
.
6. (*4) string ,
,
.
7. (*2)
:
struct X {
int i;
X(int);
operator+(int);
};
struct Y {
int i;
Y(X);
operator+(X);
operator int();
};
X operator* (X,Y);
int f(X);
X x = 1;
Y y = x;
int i = 2;
main()
{
i + 10;
y + 10;
y + 10 * y;
x + y + i;
x * x + i;
f(7);
f(y);
y + y;
106 + y;
}
X Y , .
,
.
8. (*2) INT,
int. : INT::operator int().
9. (*1) RINT,

int , - 197 + ( ), - ( ), *, /, %.
: $ (R?)INT::operator int().
10. (*3) LINT, RINT
, 64 .
11. (*4) ,
. :
, string.
12. (*2) ,
. :
INT + - ,
int INT.
,

.
13. (*3) ,
.
, .
, .
14. (*2) comlpex (#6.3.1), tiny (#6.3.2)
string (#6.9) friend .
. .
, .
5.3.
15. (*2) vec4 float.
operator[] vec4. +, -, *,
/, =, +=, -=, *=, /=
.
16. (*3) mat4 vec4.
mat4 operator[], vec4.
.
, mat4.
17. (*2) vector, vec4, ,

vector::vector(int).
18. (*3) matrix, mat4,
,

matrix::matrix(int,int).
7


- .
C++.
,


.

,
.
,
,
.

.
, .
7.1

(, ,
),

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

, , ,
, /
,
( , ..),
.
C++, #7.2,
,
. , , ,
,
.
- ,
,
. ,
,
- 199 , , ,

.
7.2

,
. ,
,
( ).
, , ,
.
7.2.1
, ,
.
:
struct employee {
//
char* name;
//
short age;
//
short department; //
int
salary;
//
employee* next;
// ...
};
next.
:
struct manager {
employee emp;
employee* group;
// ...
};

//
//
//

; employee
emp manager.
, , ,
emp . (manager*)
(employee*),
, , . ,
,
. manager*
,
emp, .
, ,
:
- 200 struct manager : employee {
employee* group;
// ...
};
manager employee , , employee
manager. manager

group employee (name, age ..).


employee manager
, .
:
void f()
{
manager m1, m2;
employee e1, e2;
employee* elist;
elist = &m1;
// m1, e1, m2 e2 elist
m1.next = &e1;
e1.next = &m2;
m2.next = &e2;
e2.next = 0;
}
, manager*
employee*. ,
employee* manager* .
7.2.2
employee manager
, ,
. :
class employee {
char* name;
// ...
public:
employee* next;
void print();
// ...
};
class manager : public employee {
// ...
public:
void print();
// ...
};
.
manager
employee? employee
manager?
employee
- 201 manager?
, ?

:
void manager::print()
{
cout << " " << name << "\n";
// ...
}

,
, . ,
this, () name
this->name. manager::print
,
, name
.
,
:
. ,

,
. ,
,
.
,
, ,
, ..
.
, friend,
,
( #5.3). :
class employee {
friend void manager::print();
// ...
};
manager::print(),
class employee {
friend class manager;
// ...
};
employee
manager. , name
manager::print().
, , . :
- 202 void manager::print()

{
employee::print(); //
// ...
//
}
, ::, print()
manager.
. :
void manager::print()
{
print();
//
// ...
//
}
, manager::print()
.
7.2.3
employee (public)
manager :
class manager : public employee {
// ...
};
, employee
manager. :
void clear(manager* p)
{
p->next = 0;
}
, next - employee
manager'. - (private)
, public:
class manager : employee {
// ...
};
, employee
manager. , manager
employee,
manager . ,
manager clear()
.
, .
, ,
, ,
. , ,

.
- 203 struct,
public . ,
struct D : B { ...

class D : public B { public: ...


, ,
class, public friend,
struct.
, ,
, .
, , $
. :
class manager : employee {
// ...
public:
// ...
employee::name;
employee::department;
};

_ :: _ ;
,
. name department
manager', salary age - . ,

.
.
, ,
,
, ()
. ,
,
.
7.2.4
derived base,
derived
base .
, base derived,
. :

- 204 class base { /* ... */ };


class derived : public base { /* ... */ };
derived m;
base* pb = &m;
//
derived* pd = pb; // : base* derived*
pd = (derived*)pb; //
,
.
.
base derived,
derived* base* .
,
base
base, derived:
class base {
int m1;
public:
int m2;
// m2 - base
};
class derived : base {
// m2 derived
};
derived d;
d.m2 = 2;
// : m2
base* pb = &d; // : ( base)
pb->m2 = 2;
// ok
pb = (base*)&d; // ok:
pb->m2 = 2;
// ok
, ,
. ,
, "".
,
,
, . , ,

m1.
.
7.2.5
. :
- 205 -

class
class
class
class
class
class
class
class

employee { ... };
secretary : employee { ... };
manager : employee { ... };
temporary : employee { ... };
consultant : temporary { ... };
director : manager { ... };
vice_president : manager { ... };
president : vice_president { ... };


.
,
. :
class temporary { ... };
class employee { ... };
class secretary : employee { ... };
// C++:
class temporary_secretary : temporary : secretary { ... };
class consultant : temporary : employee { ... };
,
.
,
. :
class temporary { ... };
class employee { ... };
class secretary : employee { ... };
// :
class temporary_secretary : secretary
{ temporary temp; ... };
class consultant : employee
{ temporary temp; ... };
,
. ,
consultant temporary,
consultant' (temporary
employee), .
.
7.2.6
.
, ,
, . :
- 206 class base {

// ...
public:
base(char* n, short t);
~base();
};
class derived : public base {
base m;
public:
derived(char* n);
~derived();
};

.
,
(. #5.5.4). :
derived::derived(char* n) : (n,10), m("member",123)
{
// ...
}
: ,
, .
: ,
.
7.2.7

, :
base*,
?
:
[1] ,
(#7.3.3);
[2] ,
;
[3] (#7.2.8).

( ) : , ,
.. 1 ,
. 2 3
,
( ) . 3 -
2, .
,
2.
:
- 207 -

enum empl_type { M, E };
struct employee {
empl_type type;
employee* next;
char*
name;
short
department;
// ...
};
struct manager : employee {
employee* group;
short
level;
//
};
, ,
:
void print_employee(employee* e)
{
switch (e->type) {
case E:
cout << e->name << "\t" << e->department << "\n";
// ...
break;
case M:
cout << e->name << "\t" << e->department << "\n";
// ...
manager* p = (manager*)e;
cout << " " << p->level << "\n";
// ...
break;
}
}
, :
void f()
{
for (; ll; ll=ll->next) print_employee(ll);
}
, ,
, ,
,
.
. -
, - case
switch .
, $,
,
, , .
- ,

print() ,
, . :
- 208 void print_employee(employee* e)
{
cout << e->name << "\t" << e->department << "\n";
// ...
if (e->type == M) {
manager* p = (manager*)e;
cout << " " << p->level << "\n";
// ...
}
}
if, ,
,
, ,
, .
7.2.8

,
, .

. :
struct employee {
employee* next;
char*
name;
short
department;
// ...
virtual void print();
};
virtual ,
print() ,
print()
.
.
, .
:
void employee::print()
{
cout << e->name << "\t" << e->department << "\n";
// ...
}
, ,
, ,

, ,
.
, .
:
- 209 struct manager : employee {
employee* group;
short
level;
// ...
void print();
};
void manager::print()
{
employee::print();
cout << "\t" << level << "\n";
// ...
}
print_employee() ,
print(),
:
void f(employee* ll)
{
for (; ll; ll=ll->next) ll->print();
}
.
:
main()
{
employee e;
e.name = ".";
e.department = 1234;
e.next = 0;
manager m;
m.name = ".";
e.department = 1234;
m.level = 2;
m.next = &e;
f(&m);
}

. 1234
2
. 1234

, , f()
,
manager ! ,
employee .
( )
.
,
.
,
.
- 210 ::,
manager::print(), ,
. manager::print()
.
, :
virtual inline (
), , ::
inline-.
,
.
,

.
7.3
, ,
,
. , ,
, ,
,
.
, ,
, .
- ,
#include. , ,
.
7.3.1
slist
, ,
,
. ent:
typedef void* ent;
ent , ,
. slink:

class slink {
friend class slist;
friend class slist_iterator;
slink* next;
ent e;
slink(ent a, slink* p) { e=a; next=p;}
};
ent,
slist:
- 211 class slist {
friend class slist_iterator;
slink* last;
// last->next -
public:
int insert(ent a); //
int append(ent a); //
ent get();
//
void clear();
//
slist()
{ last=0; }
slist(ent a) { last=new slink(a,0); last->next=last; }
~slist()
{ clear(); }
};
,
,
ent', . ,
slink' slist',
.
7.3.2
slist .
- , , ,
get() - .
#7.3.4. slist.
,

append() insert():
- 212 int slist::insert(ent a)
{
if (last)
last->next = new slink(a,last->next);
else {
last = new slink(a,0);
last->next = last;
}

return 0;
}
int slist::append(ent a)
{
if (last)
last = last->next = new slink(a,last->next);
else {
last = new slink(a,0);
last->next = last;
}
return 0;
}
ent slist::get()
{
if (last == 0) slist_handler("get fromempty list");
//
slink* f = last->next;
ent r f->e;
if (f == last)
last = 0;
else
last->next = f->next;
delete f;
return f;
}
, slist_handler (
#7.3.4).
, .
:
(*slist_handler)("get fromempty list");
slist::clear(), , :
void slist::clear()
{
slink* l = last;
if (l == 0) return;
do {
slink* ll = l;
l = l->next;
delete ll;
} while (l!=last);
}
- 213 slist ,
. ,
slist, slink, slist_iterator ,

. ,
#6.8:
class slist_iterator {
slink* ce;
slist* cs;
public:
slist_iterator(slist& s) { cs = &s; ce = cs->last; }
ent operator()() {
// 0
// ,
ent ret = ce ? (ce=ce->next)->e : 0;
if (ce == cs->last) ce= 0;
return ret;
}
};
7.3.3
slist .
, void*?
, slist ,
.
C++.
; -
struct name {
char* string;
// ...
};
,
. e
slist',
. nlist,
slist:
#include "slist.h"
#include "name.h"
struct nlist : slist {
void insert(name* a) { slist::insert(a); }
void append(name* a) { slist::append(a); }
name* get()
{}
nlist(name* a) : (a) {}
};
slist ,
. nlist -
, slist.
- 214 -

ent void*,
name*,
(#2.3.4).
,
:
struct classdef {
nlist friends;
nlist constructors;
nlist destructors;
nlist members;
nlist operators;
nlist virtuals;
// ...
void add_name(name*);
classdef();
~classdef();
};
:
void classdef::add_name(name* n)
{
if (n->is_friend()) {
if (find(&friends,n))
error("friend redeclared");
else if (find(&members,n))
error("friend redeclared as member");
else
friends.append(n);
}
if (n->is_operator()) operators.append(n);
// ...
}
is_iterator() is_friend()
name. find() :
int find(nlist* ll, name* n)
{
slist_iterator ff(*(slist*)ll);
ent p;
while ( p=ff() ) if (p==n) return 1;
return 0;
}
,
slist_iterator nlist. ,-
nlist', #7.3.5. nlist , ,
:
- 215 -

void print_list(nlist* ll, char* list_name)


{
slist_iterator count(*(slist*)ll);
name* p;
int n = 0;
while ( count() ) n++;
cout << list_name << "\n" << n << "members\n";
slist_iterator print(*(slist*)ll);
while ( p=(name*)print() ) cout << p->string << "\n";
}
7.3.4
, ,
slist
( C++ ):
[1]
;
[2]
;
[3] , slist;
[4] ,
.
,
,
.
.
, , .
,
slist.
, ,
(
/ istream ostream; #8.4.2). , , ,
,
. ,
.
.
, ,
. , , ,
, . ,

.
, ,
,
(#4.5),
.
3 4 (
), , .
, slist,
, , ,
,

, , , .
:
- 216 typedef void (*PFC)(char*); //
extern PFC slist_handler;
extern PFC set_slist_handler(PFC);
set_slist_hanlder()
.
,
cerr,
exit():
#include "slist.h"
#include
void default_error(char* s)
{
cerr << s << "\n";
exit(1);
}
,
, :
PFC slist_handler = default_error;
PFC set_slist_handler(PFC handler);
{
PFC rr = slist_handler;
slist_handler = handler;
return rr;
}
, set_slist_hanlder()
slist_hanlder().
.
, slist
, ,
, .
:
{
PFC old = set_slist_handler(my_handler);
// , slist
// my_handler
set_slist_handler(old); //
}

, slist_hanlder
slist,
.
- 217 7.3.5
,
(classdef*, int, char* ..) ,
nlist: slist.
( ),
"". ,
C (#4.7 #.11.1),
.
.
, (generic) slist,
gslist, .
:
#include "slist.h"
#ifndef GENERICH
#include
#endif
#ifndef ,
,
. GENERICH .
name2(),
, :
#define gslist(type) name2(type,gslist)
#define gslist_iterator(type) name2(type,gslist_iterator)
, ,
gslist_iterator():

gslist()

#define gslistdeclare(type)
\
struct gslist(type) : slist {
\
int insert(type a)
\
{ return slist::insert( ent(a) ); }
\
int append(type a)
\
{ return slist::append( ent(a) ); }
\
type get() { return type( slist::get() ); }
\
gslist(type)() { }
\
gslist(type)(type a) : (ent(a)) { }
\
~gslist(type)() { clear(); }
\
};
\
\
struct gslist_iterator(type) : slist_iterator {
\
gslist_iterator(type)(gslist(type)& a)
\
: ( (slist&)s ) {}
\

type operator()()
\
{ return type( slist_iterator::operator()() ); } \
}
\ ,
.
,
nlist, :
- 218 #include "name.h"
typedef name* Pname;
declare(gslist,Pname); // gslist(Pname)
gslist(Pname) nl;

// gslist(Pname)

declare () .
,
gslistdeclare, . declare
.
name*, typedef.
,
.
,
, . gslist
#7.6.2.
7.3.6
slist - .
. ,
, ,
. ,
. , :
#include "slist.h"
class iqueue : slist {
// sizeof(int)<=sizeof(void*)
public:
void put(int a) { slist::append((void*)a); }
int det()
{ return int(slist::get()); }
iqueue()
{}
};
:
( ),
int,
, iqueue.
. - , ,
:

#include "slist.h"
class stack : slist {
public:
slist::insert;
slist::get;
stack() {}
stack(ent a) : (a) {}
};
"
":
- 219 #include "stack.h"
class cp : stack {
public:
void push(char* a) { slist::insert(a); }
char* pop() { return (char*)slist::get(); }
nlist() {}
};
7.4

.
.

. ,
,
- , ,
-.

, .

. , slist, ,
, slink, .
,
, ,
. next
, ,
slink. ,
olink next, olist,
olink. olist
, olink.
"o" , ,
olist:
struct olink {
olink* next;

};
olist slist. ,
olist olink
:
class olist {
olink* last;
public:
void insert(olink* p);
void append(olink* p);
olink* get();
// ...
};
olink name:
- 220 class name : public olink {
// ...
};
,
.
, olist, . ,
, olink'.
,
olist. :
void f()
{
olist ll;
name nn;
ll.insert(&nn);
// &nn
name* pn = (name*)ll.get(); //
}
: ,
olist :
class olist : public olist {
// ...
name* get() { return (name*)olist::get(); }
};
name olist.
, ,
, . , shape
.
, slist
olist, .

.
7.5
. ,
.
.
. , ,
, .
, . ,
,
,
.
-
-. ,
.
,
(
), (
).
- 221 7.6

.
:
[1] :
, ;
;
[2] :

;
[3]

,
, ,
.
(
).

,
,
. .
,
, .
,
,
.
- ,
.
7.6.1

C (
C++), .
,
: C ( ,
, ..),
,
.. ,
, C ,
, C++
.
,
put_point() put_line(),
point:
- 222 // screen.h
const XMAX=40, YMAX=24;
struct point {
int x,y;
point() {}
point(int a, int b) { x=a; y=b; }
};
overload put_point;
extern void put_point(int a, int b);
inline void put_point(point p) { put_point(p.x,p.y); }
overload put_line;
extern void put_line(int, int, int, int);
inline void put_line(point a, point b)
{ put_line(a.x,a.y,b.x,b.y); }
extern void screen_init();
extern void screen_refresh();
extern void screen_clear();
#include
put
screen_init(),

screen_refresh(). , ""
("refresh")
.
:
#include "screen.h"
#include
enum color { black='*', white=' ' };

char screen[XMAX][YNAX];
void screen_init()
{
for (int y=0; y=a || a<=b) y0 += dy, eps -= two_a;
}
}
:
void screen_clear() { screen_init(); } //
void screen_refresh()
//
{
for (int y=YMAX-1; 0<=y; y--) {
//
for (int x=0; x
7.6.2
(shape).
, ( )
(, ), ,

, shape:
struct shape {
shape() { shape_list.append(this); }
virtual
virtual
virtual
virtual
virtual

point
point
point
point
point

north() { return point(0,0); } //


south() { return point(0,0); } //
east() { return point(0,0); } //
neast() { return point(0,0); } // -
seast() { return point(0,0); } // -

virtual void draw() {};


virtual void move(int, int) {};

//
//

};
,
move(), draw().
,
,
( ).
, , .

. shape::shape()
shape_list. gslist,
, ,
#7.3.5.
:
typedef shape* sp;
declare(gslist,sp);

typedef gslist(sp) shape_lst;


typedef gslist_iterator(sp) sp_iterator;
shape_list :
shape_lst shape_list;
, .
,
. ,
: . :
- 225 class line : public shape {
/*
'w' 'e'
north() ``
''
*/
point w,e;
public:
point north()
{ return point((w.x+e.x)/2,e.ydraw();
screen_refresh();
}
- 227 , , ().
, , south()
north() :
void stack(shape* q, shape* p) // p q
{
point n = p->north();
point s = q->south();
q->move(n.x-s.x,n.y-s.y+1);
}
,
,
, ,
,
.

.
7.6.3
.
my_shape ( ),

, .
my_shape:
#include "shape.h"
class myshape : public rectangle {
line* l_eye;
//
line* r_eye;
//
line* mouth;
//
public:
myshape(point, point);
void draw();
void move(int, int);
};
- ,
my_shape:
myshape::myshape(point a, point b) : (a,b)
{
int ll = neast().x-swest().x+1;
int hh = neast().y-swest().y+1;
l_eye = new line(
point(swest().x+2,swest().y+hh*3/4),2);
r_eye = new line(
point(swest().x+ll-4,swest().y+hh*3/4),2);
mouth = new line(
point(swest().x+2,swest().y+hh/4),ll-4);
}

shape_refresh(),
- 228 my_shape, .

my_shape. .
,
draw():
void myshape::draw()
{
rectangle::draw();
put_point(point(
(swest().x+neast().x)/2,(swest().y+neast().y)/2));
}
my_shape
rectangle l_eye, r_eye mouth
( , ):
void myshape::move()

{
rectangle::move();
l_eye->move(a,b);
r_eye->move(a,b);
mouth->move(a,b);
}
, ,
:
main()
{
shape* p1 = new rectangle(point(0,0),point(10,10));
shape* p2 = new line(point(0,15),17);
shape* p3 = new myshape(point(15,10),point(27,18));
shape_refresh();
p3->move(-10,-10);
stack(p2,p3);
stack(p1,p2);
shape_refresh();
return 0;
}
, shape_refresh()
stack() , ,
(, , )
.
- 229 ***********
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
***********
*****************
*************
*
*
* **
** *
*
*
*
*
*
*
*
* ********* *
*
*
*************
7.7

slist, ,

slink. slink -
, ,
.
,
#5.5.6. slink new
delete slist,
.
this,

, this
,
. this,
,
. :
- 230 #include
struct base { base(); };
struct derived : base { derived(); }
base::base()
{
cout << "\tbase 1: this=" << int(this) << "\n";
if (this == 0) this = (base*)27;
cout << "\tbase 2: this=" << int(this) << "\n";
}
derived::derived()
{
cout << "\tderived 1: this=" << int(this) << "\n";
this = (this == 0) ? (derived*)43 : this;
cout << "\tderived 2: this=" << int(this) << "\n";
}
main()
{
cout << "base b;\n";
base b;
cout << "new base b;\n";
new base;
cout << "derived d;\n";
derived d;
cout << "new derived d;\n";
new derived;
cout << "at the end\n";
}


base b;
base 1: this=2147478307
base 2: this=2147478307
new base;
base 1: this=0
base 2: this=27
derived d;
derived 1: this=2147478306
base 1: this=2147478306
base 2: this=2147478306
derived 1: this=2147478306
new derived;
derived 1: this=0
base 1: this=43
base 2: this=43
derived 1: this=43
at the end

this, ,
- 231 . -
this, ,
this *.
7.8
1. (*1)
class base {
public:
virtual void iam() { cout << "base\n"; }
};
base iam() ("
"), .
iam().
base* iam()
.
2. (*2) (#7.6.1)
.
3. (*2) triangle () circle
().
4. (*2) , ,
, " "
.
5. (*2) , line
rectangle .

6. (*2) ,
.
7. (*2) ,
.
,
,
.
8. (*2) .
9. (*4) ,
( ).
X, X::X(X&), X::~X()
X::operator=(X&).
10. (*5)
, . : .
- , .
task (- ). task

( task::save() task::restore()),
____________________
* , . ,
( - .)
derived::derived() :
if (this == 0) this = (derived*)43;
, d base::base()
. ,
, . (. )
- 232 .
, task.
, ,
.
().
,
.

task::delay(), "" .
task -
, .
.
queue (). ,
.
. ,
?
8

C++ /.

;
.
/
,
,
, .
.
, ,
.
8.1
/

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

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

.
/, UNIX,
/
,
.

.


. :
- 234 put(cerr,"x = "); // cerr -
put(cerr,x);
put(cerr,"\n");
, put
. .
. <<
" "

. :
cerr << "x = " << x << "\n";
cerr - . , x
int 123,

x = 123
. , X
complex (1,2.4),
cerr
x = 1,2.4)
, x
<<, <<
.
8.2

,

.
8.2.1
ostream << (" ")
:
class ostream {
// ...
public:
ostream& operator<<(char*);
ostream& operator<<(int i) { return *this<
8.2.3
, ,
. <<?
(#6.2).
,
, , ,
. , =
(), cout=a=b
cout=(a=b).
< >,
"" "" ,
/
. , "<"
",", :

cout < x , y , z;
.
<< >> ,
, ""
"", << ,
.
:
cout << "a*b+c=" << a*b+c << "\n";
, ,
, . :
cout << "a^b|c=" << (a^b|c) << "\n";
:
cout << "a<
8.2.4
<< ,

.
,
, .
() ,
.
char*
char*
char*
char*
char*

oct(long, int =0); //


dec(long, int =0); //
hex(long, int =0); //
chr(int, int =0);
//
str(char*, int =0); //

,
;
(), . :
cout << "dec(" << x
<< ") = oct(" << oct(x,6)
<< ") = hex(" << hex(x,4)
<< ")";
x==15, :
dec(15) = oct(

17) = hex( f);

:
- 238 char* form(char* format ...);

cout<
8.2.5
virtual.
shape, (#1.18):
class shape {
// ...
public:
// ...
virtual void draw(ostream& s); // "this" "s"
};
class circle : public shape {
int radius;
public:
// ...
void draw(ostream&);
};
,
, ,
.

, << :
ostream& operator<<(ostream& s, shape* p)
{
p->draw(s);
return s;
}
- 241 next - #7.3.3,
:
while ( p = next() ) cout << p;
8.3
.
cin, cout
cerr.
.
8.3.1
ostream :
class ostream {
// ...

ostream(streambuf* s);
//
ostream(int fd);
//
ostream(int size, char* p); //
};
- .
streambuf - , ; #8.6,
filebuf, streambuf . filebuf
streambuf.
cout cerr,
/,
:
//
char cout_buf[BUFSIZE]
// "filebuf"
// UNIX' 1 ( )
filebuf cout_file(1,cout_buf,BUFSIZE);
// ostream,
ostream cout(&cout_file);
char cerr_buf[1];
// 0, ,
// UNIX' 2 ( )
filebuf cerr_file()2,cerr_buf,0;
ostream cerr(&cerr_file);
ostream #8.3.3
#8.5.
- 242 8.3.2
ostream
ostream::flush():
ostream::~ostream()
{
flush();
//
}
. :
cout.flush();
8.3.3
, ,

cin, cout cerr, ( )


. , , ,
,
, :
#include
void error(char* s, char* s2)
{
cerr << s << " " << s2 << "\n";
exit(1);
}
main(int argc, char* argv[])
{
if (argc != 3) error(" ","");
filebuf f1;
if (f1.open(argv[1],input) == 0)
error(" ",argv[1]);
istream from(&f1);
filebuf f2;
if (f2.open(argv[2],output) == 0)
error(" ",argv[2]);
ostream to(&f2);
char ch;
while (from.get(ch)) to.put(ch);
if (!from.eof() !! to.bad())
error(" ","");
}
- 243 ostream
, : (1)
( filebuf);
(2) (
filebuf::open()); ,
, (3) ostream filebuf .
.
:
enum open_mode { input, output };
filebuf::open() 0,
.
, output, .
,

(. #8.4.2).
.
,
, ,
.
( ). ,
; . 810.
8.3.4
. :
cout = cerr;
,
. ,
cin -
( . #3.1.6)
8.4
. istream,
>> (" ")
. operator>> ,
.
8.4.1
istream :
- 244 class istream {
// ...
public:
istream& operator>>(char*);
//
istream& operator>>(char&);
//
istream& operator>>(short&);
istream& operator>>(int&);
istream& operator>>(long&);
istream& operator>>(float&);
istream& operator>>(double&);
// ...
};
:
istream& istream::operator>>(char& c);
{
//
int a;
// "a"

c = a;
}
C,
isspase() , (,
, , ).
get():
class istream {
// ...
istream& get(char& c);
// char
istream& get(char* p, int n, int ='\n'); //
};
, .
istream::get(char)
; istream::get n
, p.
(,
), .
,
. get
n , , '\n'
.
, . :
cin.get(buf,256,'\t');
buf 256 ,
('\t'), get.
, cin, '\t'.

, :
- 245 int
int
int
int
int
int
int
int
int
int
int
int

isalpha(char) // 'a'..'z' 'A'..'Z'


isupper(char) // 'A'..'Z'
islower(char) // 'a'..'z'
isdigit(char) // '0'..'9'
isxdigit(char) // '0'..'9' 'a'..'f' 'A'..'F'
isspase(char) // ' ' '\t'
//
iscntrl(char) //
// (ASCII 0..31 127)
ispunct(char) // :
isalnum(char) // isalpha() | isdigit()
isprint(char) // : ascii ' '..'-'
isgraph(char) // isalpha() | isdigit() | ispunct()
isascii(char c) { return 0<=c &&c<=127; }

isascii() ,
.

,
(('a'<=c && c<='z') || ('A'<=c && c<='Z')) //
(
EBCDIC ),
, :
isalpha(c)
8.4.2
(istream ostream)
,

.
:
enum stream_state { _good, _eof, _fail, _bad };
_good _eof,
. _good,
, .
, ,
_good, .
v,
, v (
, v ,
istream ostream).
_fail _bad
. _fail ,
. _bad
.
:
- 246 switch (cin.rdstate()) {
case _good:
// cin
break;
case _eof:
//
break;
case _fail:
//
// ,
break;
case _bad:
// , cin
break;
}

z , <<
>>, :
while (cin>>z) cout << z << "\n";
, z - ,

( , ) .
,
( ,
) _good. ,
istream,
cin>>z. ,
, .
(#6.3.2).

,
, , .
, ,
. / ,
C++ ( )
(
)
/.
8.4.3 ,
,
, , ,
. :
- 247 istream& operator>>(istream& s, complex& a)
/*
complex; "f" float:
f
(f)
(f,f)
*/
{
double re = 0, im = 0;
char c = 0;
s >> c;
if (c == '(') {
s >> re >> c;
if (c == ',') s >> im >> c;
if (c != ')') s.clear(_bad); // state
}
else {
s.putback(c);
s >> re;

}
if (s) a = complex(re,im);
return s;
}
, ,
.
c ,
'(' , .
,
a ,
.
clear() (),

_good. _good
istream::clear(), ostream::clear().
. , ,
,
( ), ,
. , ,
,

.
8.4.4
, istream, ostream,
:
- 248 class istream {
// ...
istream(streambuf* s, int sk =1, ostream* t =0);
istream(int size, char* p, int sk =1);
istream(int fd, int sk =1, ostream* t =0);
};
sk , .
t () ostream,
istream. , cin cout; ,
, , cin

cout.flush(); //
istream::tie() ( ,
tie(0)) ostream istream. :
int y_or_n(ostream& to, istream& from)
/*
"to", "from"

*/
{
ostream* old = from.tie(&to);
for (;;) {
cout << " Y N: ";
char ch = 0;
if (!cin.get(ch)) return 0;
if (ch != '\n') { //
char ch2 = 0;
while (cin.get(ch2) && ch2 != '\n') ;
}
switch (ch) {
case 'Y':
case 'y':
case '\n':
from.tie(old);
// tie
return 1;
case 'N':
case 'n':
from.tie(old);
// tie
return 0;
default:
cout << ", : ";
}
}
}
(
),
. . y_or_n()
, .

istream::putback(char). "
" .
- 249 8.5
, /,
, istream ostream.
, , ,

:
void word_per_line(char v[], int sz)
/*
"v" "sz"
*/
{
istream ist(sz,v); // istream v
char b2[MAX];
//

while (ist>>b2) cout << b2 << "\n";


}

.
ostream ,
:
char* p = new char[message_size];
ostream ost(message_size,p);
do_something(arguments,ost);
display(p);
, do_something, ost,
ost ..
. ,
ost ,
_fail. , , display
"" .
, ,

,
. , ost
- .
8.6
/
,
. , ostream,
,
, ostream, .
,
(
ostream).
, ostream ,
. ,
, . ,
.
,
- 250
.
:
struct streambuf {
char*
char*
char*
char*

base;
pptr;
qptr;
eptr;

//
//
// char
// char
//

char alloc;

// , new

// :
// EOF 0
virtual int overflow(int c =EOF);
//
// EOF ,
// char
virtual int underflow();
int snextc()
// char
{
return (++qptr==pptr) ? underflow() : *qptr&0377;
}
// ...
int allocate()

//

streambuf() { /* ... */}


streambuf(char* p, int l) { /* ... */}
~streambuf() { /* ... */}
};
, ,
,
( ) inline.
overflow() underflow().
:
- 251 struct filebuf : public streambuf {
int fd;
//
char opened;
//
int overflow(int c =EOF);
int underflow();
// ...
// :
// , 0,
// "this"
filebuf* open(char *name, open_mode om);
int close() { /* ... */ }
filebuf() { opened = 0; }
filebuf(int nfd) { /* ... */ }
filebuf(int nfd, char* p, int l) : (p,l) { /* ... */ }

~filebuf() { close(); }
};
int filebuf::underflow()
// fd
{
if (!opened || allocate()==EOF) return EOF;
int count = read(fd, base, eptr-base);
if (count < 1) return EOF;
qptr = base;
pptr = base + count;
return *qptr & 0377;
}
8.7
, /
, ,
. .
" " inline-,

- . (,
..) .
, /,
.
8.8
1. (*1.5) ,

.
- 252 2. (*1.5) name_and_address (__).
<< >>.
name_and_address.
3. (*2)
. -
y_or_n() #8.4.4. : , ,
, , , ..
.
4. (*1.5) , (1)
, (2) , (3) , (4)
, C++
, (5) , (6)
, (7) , (8)
, (9) .
5. (*4) / C
() / C++
().
6. (*4) / C++

() / C
().
7. (*4) C C++ ,
.
8. (*2) , []
.
9. (*3) 8, , []
, . : , []
" ",
,
char
.
10. (*2) 9, []
, .
11. (*3) ,
10.
12. (*3.5)
.
printf.

.
istream.
13. (*4) ( ) ,
.
C++
1.
C++ - C*,
, inline-, ,
, , ,
, .
++ " " #15.
1985.
2.
: , ,
, , . ,
, ( " "), , ,
, .
,
, .
,
,
, .
2.1
/* ,

*/. . //
, ,
.
2.2 ()
-
; ; '_'
; .
2.3

:
____________________
* " " . .
. "C Programming
Language - Reference Manual" UNIX V AT&T Bell
Laboratories. (. )
- 254 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
.
2.4
, . #2.6
,
.
2.4.1
, ,
, 0 ( ),
. 8 9 .
,
0 0,
.
f F, 10
15. ,
, (long);
,

, long;
int.
2.4.2
, ,
l ( "") L,
.
2.4.3
,
(), , , ''.

().
int.
, '
\,
escape-:

NL(LF)
NT

\n
\t

- 255
VT
\v

BS
\b

CR
\r

FF
\f

\
\\
()
'
\'

0ddd
\ddd

0xddd
\xddd
Escape- \ddd ,
1, 2 3 ,
.
\0 ( ), NULL.
Escape- \xddd ,
1, 2 3 ,
.
,
.
2.4.4
,
, , (,
, ).
. ( )
; , ()
( )
. double.

2.4.5
, , (. #8.5)
int.
2.4.6
(#5)
(#4.1) .

*const; , ,
const (#8.2).
2.5
,
: "...". " "
static (. #4 ), .
, , .
() \0 ,
.
" \;
- 256 , escape-,
. , ,
\; ,- \
,- .
2.6

, .
_____________________________________________________________
|
DEC VAX-11 Motorola 68000 IBM 370
AT&T 3B |
|
ASCII
ASCII
EBCDIC
ASCII |
|___________________________________________________________|
| char
| 8 | 8 | 8 | 8 |
| int
| 32 | 16 | 32 | 16 |
| short | 16 | 16 | 16 | 16 |
| long
| 32 | 32 | 32 | 32 |
| float | 32 | 32 | 32 | 32 |
| double | 64 | 64 | 64 | 64 |
| | 32 | 32 | 24 | 32 |
| |
|
|
|
|
| float | +_10E+_38 | +_10E+_38 | +_10E+_76 | +_10E+_38 |
| |
|
|
|
|
| double | +_10E+_38 | +_10E+_38 | +_10E+_76 | +_10E+_308 |
| char | | | | |
| | | | | |

| | |
| |
|
| | | | | |
|__________|___________|___________|___________|____________|
3.


*.
.

"opt",

{ opt }
.
#14.
____________________
* !!! " " ,
!!!
- 257 4.
() , , ,
. (#8).
,
. ,
. - .
, . ,
, ,
.
4.1
: , ,
.
: , (#9.2),

. (#9.12),
,
.
,
.
: , (#9.2) (#8.5),
, ,
.
:
(#8.5.2),
(#7.1) .
(#7.1)

->. (#8.5.1)
:: ,
. ,
(#8.5.15), ,
.

.
, .
,
:: (#7.1). , ,
, ,
class, struct union (#8.2).
enum, , ,
, enum (#8.2).
4.2
(#8) , ,
, (#10),
extern (1)
, (#8.8).
- 258 4.3
, static,
.
. , .

(#5), (#8.7), (#8.5), (#8.10)
(#8.10).
,
. ,
, inline- (#8.1) const (#8.2),
, ,
(#12).

.
, const,
, const,
extern
. inline-.
4.4
: .

.

.


new delete ; . #7.2 #9.14
- 259 4.5
, (char),
,
,
.
,
short int, int long int. (long int)
, (short
int), , ,
. ""
,
; ,
.
(#8.9) .
enum int.
, unsigned,
2n, n - .
(float) (double)
.

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

(#9.1)
(#7.15). void
(#7.2).
4.4

,
:
- 260 ;
,
;

;
;
, ;
, ,

;
, ;
, ,
.

.
void* ( void)
.
5. LVALUE()
;lvalue () ,
. -
. , : ,
- , * - ,
, . "lvalue"
1=2, 1
(value) .
,

.
6.

.
,
. #6.6 ,
;
. #8.5.6
, .
6.1
,
.
.
; .
,
- 261 ; . #2.6. unsigned char
0 .

,
(), ASCII .
, , esc
; , '\377' -1.
char,
; .
6.2 Float double
float
.

, .
6.3

. ,
.
,
.

.
.
6.4

; ,
.

; int
long ; . #7.4.
6.5 Unsigned

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

. ,
.
- 262 6.6

.
" ".
-, char, unsigned char short
int.
, double,
double .
, unsigned long,
unsigned long .
, long,
long .
, unsigned,
unsigned .
int
.
6.7
, , ,
.. .
0 , ,
,
.
void*.

; . #8.5.3.

.
, ", ...", ,
,
" , ...".
- 263 6.8
, ,
.

; . #8.6.3.
7.

,
, .
, ,
+ (#7.4) - , ##7.1-7.4.
.

( ).

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

.

.
C++ ; 0


.
, #7.2-7.15,
*, ,
, ; .
#7.16.
7.1
, . , -> ,
, .
_:

_ ,
id:

____________________
*
;

..
- 264 __
typedef-
::

typedef- :: __
_:
id
::

this
(

)
_
[

]
_
( _ opt )
_
.
id
_ -> id
,
(#8). __
; . #7.16 #8.5.1.
::,
, , .
, (#4.1).
Typedef- (#8.8) , ::,
, . Typedef-
(#8.5),
. .
Typedef- ,
. typedef-
.
. int,
long double .
- 265 . - " ".

(#6.7).
this
(. #8.5) . ,
.
, ,
, ,
. ,
lvalue .
,
, . - .
" ...",
int "...".
1[2] ( ) *((E1)+(E2)).
, ,
## 7.1, 7.2 7.4,
, , * + ; , #8.4.2
.
,
, (, )
, .
", ..."
" , ...",
"...".

(#8.6). (#6.6-8)

(#8.5.6).
,
,
.

, (#8.4).
float,
, double; , ,
.
; .
.
, ,
( , typedef-
::) .
,
. ,
, .
, " " (#8.5.12)
(#8.5.13).
, ( -> ),
( ,
typedef- ::) .
,
. ,
,
. , E1->MOS ,
(*E1).MOS. #8.5.
" ..."
(. #8.4
and #8.6.3), ,
- 266 . ; .
#8.6.3.
7.2
:
_:
_

++

-sizeof

sizeof
(
_
)
(
_
)

__
(
_
)
new
_

opt
new
(
_
)
delete

delete [ ]
_:

* & - ! ~ ++ - * :

lvalue, ,
. "
...", "...".
& ,
. lvalue.
"...", "
...".
+
.
.
-
. .
.
2n, n
- int.
! 1,
0, 0, 0.
int.
.
~ .
.
.
7.2.1
++ .
. ,
. ++x x+=1.
. (#7.4)
(#7.14).
--
++.
- 267 , ++,
. . ,
, ,
++. , .
,

--, . .
, , ,
++. , .
7.2.2 Sizeof
sizeof . (
, sizeof. ,
,
char.)
.
, .
,

.
sizeof
. , ,
.
7.2.3
__ (#8.2), , ,
( _,

#8.5.5)
. ,
, _ (#8.7) .
,
. .

, . , int
long , .
, ,
,
.
#2.6.

. ,
, ,
.

.
,
,
. ,

.

. ,
- .
- 268

(#8.5.6).
&X,
X*.
7.2.4
new _ (. #8.7),
. , new,
, . new
.
, . ,
new int new int[10] int*.

(#8.6.2). new
(#7.2)
void* operator new (long);
.
. operator new()
, .
delete , new.
void. delete ,
new. delete ,
new.
delete .
, delete

void operator delete (void*);



delete [ ]
,
.

; . #8.5.8.
7.3
*, / % .
.
_:
*
/
%
* . *

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

7.4
+ - .
.
, .
_:
+
-
+ .
.

, .
,
,
. ,
P , P+1
.
.
+
.
- .
. ,
,
, .
,
( ) ,
, ,
.
int, long; . #2.6. ,

, ,
, ,
, .
7.5
<< >> .
,
.
int;
. ,
.
- 270 _:

<<

>>
1 << 2 1 (
), 2 ;
. 1 >> 2 1 ,

2 . ,
( ), 1 unsigned;
(
).
7.6
() ,
- : a < b < c , .
_:

<

>

<=

>=
< ( ), > ( ), <= >= 0,
, 1, .
int. .
;
, ,
.
.
7.7
_:

==

!=
== !=
. (, a
7.8
-: &
& , , &,
.

; .
.
7.9
__:
^
^ , , ^,
.

- 271 ;
. .
7.10
__:
|

| , , |,
.

;
. .
7.11
__:
&&
&& . 1,
, 0 .
& && ;
, , 0.
,
.
int.
7.12
__:
||
|| . 1,
, 0 .
| ||
; , ,
0.
,
.
int.
7.13
_:
? :
.
, 0,
, .
,

. ,
.
.
- 272 7.14
, .
lvalue,
, . lvalue
( , const).
,
.

_:
_
_:
= += -= *= /= %= >>= <<= &= ~= |=
=
, .
,
.
,
,
, . #6.7.
.
; . #8.5.3.
" ..."
, .
E1 op= E2
E1 = E1 op (E2); E1 .
+= -= ,
() ,
#7.4;
.
7.15
_:
,
, , ,
.
.
. ,
,
(#7.1) (#8.6),
, ,
; ,
f (a,(t=3,t+2),c)
, 5.
- 273 7.16
, ,
, (.
#8.5.11). .
.
= & ()
.

, (,
++a a+=1), ,
. , ,
, ,
lvalue; ,
.
7.16.1
, ,
(. #8.5.4),
, (. #8.5.10),
, . ,
@, x@ @x
x.@() @(x). ++ - .
7.16.2

(. #8.5.4), ,
(. #8.5.9), ,
. , @, x@y
x.@(y) @(x,y).
7.16.3

_ ( _ opt )

_ [ ]
.
operator() operator[]. x(arg)
x.operator()(arg) x.
x[y] x.operator[](y).
- 274 8.
,
; ,
. :
:
_ opt _ opt ;
_
asm_

_ ,
. _
(#10)
.
(#8.5) (#8.10), ,
_

class_

enum_. #8.8; asm


#8.11.
_:
sc_
_
_
friend
typedef
_:
_ _ opt

.
8.1
" " (sc-) :
sc-:
auto
static
extern
register
, auto, static register
,
. extern
(#4.2), -
.
register auto
() ,
. .
&.
auto register
, , .
- 275 ,
.
sc_.
sc_,
. :
.

static extern
.

:
-:
overload
inline
virtual
overload
; . #8.9.
inline ,
.
, , inline
. (#8.5.2 #8.5.10),
, inline .
virtual
; . #8.5.4.
friend

; . #8.5.9.
typedef ; . #8.8.
8.2
(_) :
_:
__
class_
enum-
__
const
const
_.
_. const
lvalue. ,
int.
- 276 __:
char
short
int
long
unsigned
float
double
const

void
long, short unsigned
. int; unsigned
char, short long.
#8.5 #8.10
.
__:
typedef-

:
class
struct
union
enum

,
. :
class x { ... };
void f(int x)
{
class x a;
// ...
}
,
__ _; . #8.8.
8.3
_, ,
,
.
_:
_
_ , _
- 277 _:
opt
#8.6.
,
. :
:

_
( )
* const opt
& const opt
( __ )

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

typedef-
~ typedef-
__
__
, .
8.4
,
, ,
, .
_;
.
(. #8.5.2) , _
.

, , ,
.
,
.

T D1
T - ( int ..), D1 - .
, "...
T", "..." , D1
( x "int x" int). ,
D1
*D
- 278 "... T."
D1
* const D

"...
T", , , *D, lvalue.
D1
&D

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

=
_
_ =

__ ,
,
; ,
.
,
.
__

.
, .
,
.
. ,
,
.
- 279 .
, ,

.
(#10),
.
D1
D[ _]

D[]
"...
T". _ ,
,
int. ( #12.)
" ",
; , ,
.
, ,
, , .
,
.
, .
,
,
( ).
, ,
. :
,
; ,
.
8.4.1
,
- 280 int
int
int
int
int

i;
*ip;
f ();
*fip ();
(*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: , 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 (#8.2).
point (int = 0,int = 0);
, ,
int.
- 281 point (1,2);
point (1)
point ()

/* point (1,0); */
/* point (0,0); */

printf (char* ... );


,
.

printf ("hello, world");


printf ("a=%d b=%d",a,b);
printf ("string=%s",st);
, char*.
,
float fa[17], *afp[17];

. , ,
static int x3d[3][5][7];
, 3x6x7. : x3d
;
;
. x3d, x3d[i],
x3d[i][j], x3d[i][j][k] .
"", int.
8.5
. typedef- (.
#8.8),
.
.
_:
_
{
_
opt
}
_
{ _ opt public :
_
opt
}
_:

opt
opt : public opt typedef-
:
class
struct
union
, ; .
#8.5.8. ,
; . #8.5.12.
: , , , ,
. #8.5.13.
, ; . #8.5.8.
- 282 _:
_ _ opt
_:
_
opt
_;
_:

opt :
_

, ,
. , cl
cl,
cl.

.
:
struct tnode
{
char tword[20];
int count;
tnode *left;
tnode *right;
};
20 ,
. ,
tnode s, *sp
s sp
.
sp->count
count , sp;
s.left
s;
s.right->tword[0]
tword
s.
8.5.1
- static; - .
auto, register extern.
,
. mem cl
cl:mem, . ,
cl.
- 283 8.5.2
, , ( friend (#8.5.9))

(#7.1). :

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);

. ,
.
,

typedef- . __
. 3.3. #10.1. :
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 -
(. #10.1).
this ,
. this ,
cl, cl*. mem - cl, mem
this->mem - cl ( mem

).
(#10.1) .


inline (#8.1) .
:
- 284 -

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

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

overload (#8.2):
, (. #8.9).
.
(...),
, (#8.4).

,
.
8.5.3

:public opt typedef-
typedef- ,
, . ,
.
, ,
,
;
(#7.1):
typedef- ::
:
- 285 struct base
{
int a;
int b;
};
struct derived : public base
{
int b;

int c;
};
derived d;
d.a = 1;
d.base::b = 2;
d.b = 3;
d.c = 4;
d.
.
8.5.4
base () virtual (#8.1)
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.
,
,
, .
,
, ,
.
- 286 ,
,
. (friend)
(#8.5.9). f , ,

f, .
.
, ,
.
, ,
.
8.5.5
, ,
. ;
.
,

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

. ,
,
, . ,
, . #8.6.2,
,
, . #17.
8.5.6
, ,
.

. X ,
X, X
,
.
(#7.1) (#8.6).
:
- 287 class X { ... X (int); };

f (X arg)
{
X a = 1;
a = 2;
f (3);
}

/* a = X (1) */
/* a = X (2) */
/* f (X (3)) */

X ,
,
,
X. :
class X { ... X (int); };
class X { ... Y (X); };
Y a = 1;

/* : Y (X (1)) */

8.5.7
cl ~cl .

; cl
.
overload, virtual friend.

.
, . #17.
8.5.8
, class,
, ,
(#8.5.2) (. #8.5.10),
public: . .
.
, ; . #8.5.11.

public,
; ,
. mem base

typedef- . ;
typedef- ,
.
.

- 288 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.
8.5.9 (friends)
-,
.
:
class private
{
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
- 289 class cl2
{

friend cl1;
...
};
8.5.10
,
.
__: operator op
op:
+ - * / % ^ & | ~
! = < > += -= *= /= %=
^= &= |= << >> <<= >>= == !=
<= >= && || ++ -- () []
- .
,
. . #7.16.
8.5.11
, . ,
struct s { ... };

class s { public: ... };


(
).
8.5.12
,
0,
.
.
(
).
8.5.13

opt: _
; .
;
. , ,
. .
,
; . #2.6.
- 290

().
0 .
, .
, unsigned.
unsigned.
&,
.
.
8.5.14
.

.
,
.

.
:
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.
8.6

. =,
, .
- 291 -

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

}
}

_
:

_
,
_
{ _ }

, #15,
, ,
.
,
, .
,
"
"*. (
), ,
, .
; ,
.
, () , "X
a();" X, ,
X.
8.6.1
( ),
,

, .
,
.
, ,
.
.
,
;
, , ,
. , ,
, ,
,
.
,
int x[] = { 1, 3, 5 };
x ,
, .
____________________

* "garbage", [],
.. , 0, char, '\0',
, (*) NULL.
- 292 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. c

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 (
) .
8.6.2

, ;
. ,
, ,
.

. :
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);

; . ,
- 293 complex
complex
complex
complex

zz1
zz2
zz3
zz4

=
=
=
=

complex (1,2.3);
complex (123);
123;
zz3;

,

, .
, ,

.
.
,
.
8.6.3
T&, " T",
T,
T.
&. :
int i;
int& r1 = i;
int& r2 = &i;
r1 r2 i.
,
. #7.1,
.
r1 = r2;
, r2, ,
r1.
. ,
.
pp, ,
rr, pp=&rr.
pp=&*rr.
T
,
T.
. , ,
, . :

double& rr = 1;
, rr double,
1.0.
.
- 294 8.6.4

char.
. :
char msg[] = "Syntax error on line %d\n";
,
.
8.7
(
sizeof new) .
" "
, .
_:
_ _
_
:

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

_,
, .
,
. :
int
int
int
int
int

*
*[3]
*()
(*)()

, , "", " ",


" ", ",
, " " ".
,
.
__:
typedef-

char
short
int
long
unsigned
float
double

. :
- 295 (double) a

double (a)
8.8 typedef
, _ typedef,
, ,
,
.
typedef-:

, typedef,
, - ,

, ,
, #8.4.
typedef-. ,
typedef int MILES, *KLICKSP;
struct complex { double re, im; };

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;
.

_:

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


.
&.
, #6.6,


char->short->int, int->double, int->long float->double. ,
- overload
; . #8.2.
:
overload abs;
int abs (int);
double abs (double);
,
,
. , 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"))
*/
- 297
.

8.10
int .
enum_:
enum
opt
{
enum_
}
enum_:

enum_,

= _
enum-
, .
=,
0 1
. =
;

.

.
.

enum_ ;
. :
enum color { chartreuse, burgundy, claret=20, winedark };
...
color *cp, col;
...

col = claret;
cp = &col;
...
if (*cp == burgundy) ...
color , ,
cp .
{ 0, 1, 20, 21 }.
8.11 Asm
Asm
asm ();
asm .
.
- 298 9.

.
9.1
,

;

.
9.2 ,
( "", )
,
:
_:
{ _ opt _ opt }
_:

_
_:

_
- _
,
, .
auto register
. ;
. ,
static (#4.2)
.

9.3

if ( )
if ( ) else
, ,
.
, 0. ,
"else" , else
if, else.
9.4 while
while
while ( )
- 299 ,
.
.
9.5 do
do
do while ();
,
.
.
9.6 for
for
for ( _1 opt ; _2 opt ; _3 opt )

:
- 300 _1;
while

(_2)
{

_3;

}
;
,
, ;
,
.
.
_2 while-

while(1);
.
9.7 switch
switch
.

switch ( )
.

case :
case
_ :
; .
switch , case,
.
#15.

default :
switch,
case .
,
, case.
case , default,
, .
case default ,
switch .
case default
, ,
. switch . break, #9.8.
switch .
,
.
9.8 break

break ;
- 301 while, do, for
switch ; ,
.
9.9 continue

continue ;

while, do for;
. ,

while (...)
{
...
contin:;
}

do
{
...
contin:;
}
while (...);

for (...)
{
...
contin:;
}

continue goto contin. ( contin:


, #9.13.)
9.10 return

return, :
return ;
return ;
,
, .. void.
,
;
. , ,
, ,
. return
.
9.11 goto

goto ;
(#9.12),
.
9.12
,
:
.
goto.
- 302 , ,
. . #4.1.
9.13

;

} ,
, while, .

9.14 delete
delete
delete ;
. ,
, . ,
delete ,
; . #17. delete
, new (#7.1), .
, .
9.15 asm
asm
asm ( ) ;
asm .
.
10.
C++
.
static .
(#8.2) ,
int.
, , ,
. ,
, ,
( )
.
10.1

_:
_ _ opt __
opt
_
c (sc-c),
, extern,
- 303 static, overload, inline virtual.
", ...", ,
.

_:
( __ )
#8.4.
, , ,
,

, .
,
.

_:
_
:
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.
10.2

_:

.
,

- 304 , ( ),
.
11.

. #4.1.
12.
C++ ,
,
. , #, .
;
,
( )
.
, const inline
#define.
12.1

#define _

, .
( ) .

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

( define) .

.

\ .

#undef
.
- 305 12.2

#include "_"
_.

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

#if
, -.
,
#15;
:
sizeof .
C
defined.
-,
#define
#undef; 0.

#ifdef
,
; , #define.

#ifndef
,
.

, ,
#else

#endif
, #else
#endif . ,
#else , #else, #endif,
.
.
12.4
, C,

#line "_"
, ,
, ,
- 306 .
, .

13.
. #8.1.
14.
,
.
14.1
,
. , ,
, , ;
. #8.5.10.
14.2
, :
.
,
. ,

typedef int (*PF) ();


extern g (PF);
extern f ();
...
g (f);
g :
g (PF funcp)
{
...
(*funcp) ();
...
}
, f ,
g(f) (.
14.3 ,
,
, . -
.
[] ,
- 307 E1[E2] *((E1)+(E2)). ,
+, E1 E2 , E1[E2]

E2- E1. , ,
.

. E n- i*j*...*k,
E (n-1)-
j*...*k. , ,
, *,
(n-1)- , ,
.
, ,
int x[3][5];
x - 3*5. x
, ( )
5 . x[i], *(x+1), x
, , , 1
x, 1
, , 5
. ,
( 5 ),
.
, ;
.
, C
( ),

,
,
.
14.4
, , ,
.
, . ##7.2 8.7.
,
. , int long
, .
, ,
, .
#2.6.
.
,
, ,
.

.
, ,
. ,

.
- 308 -

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

double; .

.
, - .
15.
C++ ,
: (#8.3), case
(#9.7), ,
, (#8.3), (#8.6).
,
, , , sizeof
, ,
+ - * / % & | ^ << >> == != < > <= >= && ||

-~!

?:
,
.

; , ,
,
& ,
,
. &
.
,

.
#if:
, , sizeof
.

- 309 16.
C++ .

, .
, ,
, ,
, .
. ,
(
) ,
, .
.
,
, ,
. ,
"" ;
register .

. , -
, .
.
, .



.

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

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

, ,
. _delete() ,
_new(), ,
_delete() .
delete .
- 310 _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 -,
(
), .
this,
( )
,
.
this,
(
) .
18.
, C++
. .
18.1
:

:
_
:

&

!
~
++
--
++
-(
_)
__

_)

- 311 sizeof

sizeof
(
_
)
new
_
new ( _ )
:
id
::

this
(

)
[

(
_
opt
)
.id
->id
id:

typedef- ::
_:

_,
:
_
_
_
, :
_:
*
/
%
+
<<
>>
<
>
==
!=
&
^
|
&&
||
= += -= *= /= %= ^= &= |= >>= <<=
_:
* & - ~ ! ++ -_:

()
[]
_:
_ _
_:

*
_
_ ( __ )
_ [ _ opt ]
( _ )
__:
typedef-
char
short
int
long
- 312 unsigned
float
double
typedef-:

18.2
:
_ opt _ opt ;
_
asm-
_:

;
enum ;
:
class
struct
union
asm-:
asm ( );
_:
_ _ opt
_:
__
_
enum_
sc_
_
typedef
friend
const
void
sc_:
auto

extern
register
static
-:
inline
overload
virtual
_:
-
- , _
-:
opt
:
_
(

)
*
const
opt

&
const
opt

(
__
[ _ opt ]

- 313 _:
__
typedef- . __
__:

typedef-
typedef-
__
__:

- 314 __:
__ opt ... opt
__
:
__
,
_
_
_:
_

_ = _
_:
_
{_
opt
}
_ {_
opt public :
_ opt }
_
:

opt
opt : public opt typedef-
_
:
_ _ opt
_:

_ opt _ ;
_:

opt : _
:
=

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

_
, _
{ _ }
enum-:
enum opt { enum- }
enum-:

enum- ,
:

= _
18.3
_:
{ _ opt _ opt }
_:

_
_:

_
:

;
if
(

if ( ) else
while
(

- 315 do

while
(

)
;
for ( opt ; opt ; opt )

switch
(

case

default
:

break;
continue;
return

opt
;
goto

delete

;
asm
(

)
;

;
18.4
:
_
_
_:
_

_:
_
opt
_
__ opt _
_:
( __)
_:
_
__:
: ( _ opt )
18.5
#define _
#define ( ,..., )
#else
#endif
#if
#ifdef
#ifndef
#include "_"
#include <_>
#line "_"
#undef
- 316 19. " C"
19.1
(#8.4)
(#7.1). .

; #6.2.
; #8.6
; 7.16, #8.5.10.
inline- ; #8.1.
(const); #8.3.
; #8.3, #8.6.3
new delete ;
#17.
(#8.5.8),
(#8.6.2),

(#8.5.6),
(#8.5.4).
; #8.5.
[] void*
; #7.14.