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

(. . .) .

http://www.stolyarov.info

++,
2011 2012 , , - . , , , ,
.
,
, .
, ,
, , ,
, .


, , :
1. ( )
, ;
2. ,
, : (1)

PDF, , , ,
,
; (2)

, ,
,
,
. .
. ,
: - , , ,
- ; -, , ,

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

, -

. .

. .

++

 2012

004.432.2
32.973.26

81

. .
81 ++: .  3- . 
.: , 2012.  128 .: .

, -
++. . ++
;
.
,
; ++ .
, - .
004.432.2
32.973.26


++
-
31.01.2012 .
60x90 1/16. ... 8. 200 . 032.
 
00510 01.12.99 .
11992 -2, , ,
. .., 2- , 527 .
. 939-3890, 939-3891. ./ 939-3891

c . . , 2012


++ (  ).
, ; ?
++ , , . . , ,
.
, , ++, : ,
, .
- , ;
, ,
++ .
++ , , (
19981999 .) ++,
iostream, ; ,
, , 
. , -
++, , ,
. , , ,
.
,
++
,
.
, ++

,
. ++ .
, ++ 1999 ,
,
 , , ,

.
3

, ,
++ , , ,
, #include <stdio.h>
#include <iostream>,  ! 
using namespace std;, printf
cout,
, list<>. ,
, , ++
. , ++ ,
.
,
, , ++, .
,
. ,
iostream , ,
.

++ ,
 ( , ). , ,
, ;
- ,
.
,
. ++, (, ).
, .
, , .
: (1) ; (2) ; (3) ,
(4) 4

().
,
++, , ,
, . ;
, . .
++, (namespaces) , . , , , ,
++, . - , ,
-
. , , (). , :
, .

Unix (, Linux
FreeBSD). ,
. Windows , , ,
. , Unix ( , ),
.
, , ,
++ , ; http://www.stolyarov.info.


,  ,
++ - .
, , - 5

; , - ,
 .
++, 
,
, .
++
(STL); ,

.

, ( ).
, , , ( , , ).
, ++, , , ,
++. () ,
, , ; 1 . , ,
, ,
++ , .
,
, . ,
STL , ;
, , ,
++.
1997 ++
, ++. STL
,
.
1999 . ( ) ,
++ ,
, . ,
1 , ,
Linux.

++ ,
STL, , , ,
( )
++ STL , , , .
, , , STL (!),
.
++ ; , . ,
, - ,
. , , . ,
, , .

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

, . , , -

 . - .
,  , ,
.
http://www.stolyarov.info/books/cppintro. , ,
.
7

1.
1.1.
-
70- XX . Smalltalk
- , .
, , . , (
,  , ). , ,
, , 
; , ,
.
() . ,
, , , ,  , ,
, .
-
.
,
 .
( 8

 , ).
,  . , 2 + 3 -

, , 5. , , , - ,
.

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

.

, -
;
, ,

. , - ,
,

( ++) ,
.

, .
, ;
- ,
++.
1 , , , ,
, .

1.2. ++
++ 80
- . ++
-
. , ++ , -
.
, ,
++.
++. , ++ c , .
, , , :

int try;
++,
try  ++. , ++
; ,

struct mystruct {
int a, b;
};

++
mystruct,

. , ,

typedef struct mystruct {


int a, b;
} mystruct;
++ - ( , . .
).
, ++
typedef, ,
struct, (
,
struct). ,

struct s1 {
int x, y;
};
10

++ s1:

s1 a;
struct:

struct s1 a;
(, ++ ).
++ , , , , ,
. , , :
, , , , , . ++ : , .
-,
: , int* double* ++,
. ++
void*
,
.
++ (
) , , . .
-, ++ , , (,
, ).
. -, ++ , /* */,
, //; , ,
.
, .

11

2.

2.1. ,

, ++ , ( ++) .

2.1.1. - ()
-
++ - .
, , .

:

struct str_complex {
double re, im;
};
.
:

double modulo(struct str_complex *c)


{
return sqrt(c->re*c->re + c->im*c->im);
}
++ , modulo() .
,
:
12

struct str_complex {
double re, im;
double modulo() { return sqrt(re*re + im*im); }
};
,
, , ,
, .
, , :

str_complex z;
double mod;
z.re = 2.7;
z.im = 3.8;
mod = z.modulo();

modulo()
str_complex.
(  z), ,
. ,
,
,
,
. z,
re im z.re
z.im.
 , -
.
,
. , , ,

z
modulo, ;
, double, ; ,
mod.

2.1.2. this
, - () ,
, .
, modulo, , modulo,
, 
;
13

. , -

 , .
;
this. this , A*, A  .
, :

struct str_complex {
double re, im;
double modulo() {
return sqrt(this->re*this->re + this->im*this->im);
}
};
, , this ; ,
- ( ), , .

2.1.3. .
,
. , re im , str_complex.
, , ++
,
( , -)
, -.

public private, , (public:) , ,
- (private:)1 . .

struct str_complex {
private:
double re, im;
public:
double modulo() { return sqrt(re*re + im*im); }
};
1

protected.
14

re im modulo().
, ,
, . . re im. , , . 13, , ,
. , .
, , :

struct str_complex {
private:
double re, im;
public:
void set(double a_re, double a_im)
{ re = a_re; im = a_im; }
double modulo()
{ return sqrt(re*re + im*im); }
};
, , :

str_complex z;
double mod;
z.set(2.7, 3.8);
mod = z.modulo();
2 . ,
z set()
( z)
, . .
. ,
. ,

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

2 , .

15

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

struct str_complex {
private:
double re, im;
public:
str_complex(double a_re, double a_im)
{ re = a_re; im = a_im; }
double modulo()
{ return sqrt(re*re + im*im); }
};
(- str_complex), , str_complex
double, , . ,
double: ,
 .

, ++ . (), , .
:

str_complex z(2.7, 3.8);


double mod;
mod = z.modulo();
, , . :

double mod = str_complex(2.7, 3.8).modulo();



str_complex modulo().
.
, ,
16

str_complex
, ,

str_complex z;
. ,
; , , 2.4.
,
++ . ,
,

int v(7);
,

int v = 7;
.
++ , ( )
. , -

(,
), .

2.1.4.
, - . , .
, str_complex
, . , . ,
, ,
. , ,
. , -
, , ,
, .
, , ,
, , re im. , re im , ,
17

mod arg (. . ), , , .
(
), ,
. ., , ,
, .
,
, .
,
,
, 3 :

struct str_complex {
private:
double re, im;
public:
str_complex(double a_re, double a_im)
{ re = a_re; im = a_im; }
double get_re() { return re; }
double get_im() { return im; }
double modulo() { return sqrt(re*re + im*im); }
double argument() { return atan2(im, re); }
};
re im , , ,
,
, , , . , get_re()
get_im() , , modulo() argument():

struct str_complex {
private:
double mod, arg;
public:
str_complex(double re, double im) {
mod = sqrt(re*re + im*im);
arg = atan2(im, re);
}
3 , atan2() .

18

};

double
double
double
double

get_re() {
get_im() {
modulo() {
argument()

return mod * cos(arg); }


return mod * sin(arg); }
return mod; }
{ return arg; }


str_complex, . , , , , , ,
, . ,
,
.
, , ,
, ,
,
:

struct str_complex {
private:
double re, im, mod, arg;
public:
str_complex(double a_re, double a_im) {
re = a_re; im = a_im;
mod = sqrt(re*re + im*im);
arg = atan2(im, re);
}
double get_re() { return re; }
double get_im() { return im; }
double modulo() { return mod; }
double argument() { return arg; }
};
, , , , ,
,
(  (re,im)
(mod,arg) , ). ,
; ,
19

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

, ++ , , , .

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

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

class Complex {
20

double re, im;


public:
Complex(double a_re, double a_im)
{ re = a_re; im = a_im; }
double get_re() { return re; }
double get_im() { return im; }
double modulo() { return sqrt(re*re + im*im); }
double argument() { return atan2(im, re); }
};
, public:,
,
- . public: , . . , (
- Complex(...), modulo() .)
.
, ,  .
, , ++. , ,
(, ),  , ,
.

2.2.


, . ,
, , .
++ . , , . -,
.
, .
,
, , . : . 17,
21

, . ,
:
class Complex {
double re, im;
public:
Complex(double a_re, double a_im)
{ re = a_re; im = a_im; }
double modulo() { return sqrt(re*re + im*im); }
double argument() { return atan2(im, re); }
double get_re() { return re; }
double get_im() { return im; }
Complex operator+(Complex op2)
{
Complex res(re + op2.re, im + op2.im);
return res;
}
Complex operator-(Complex op2)
{
Complex res(re - op2.re, im - op2.im);
return res;
}
Complex operator*(Complex op2)
{
Complex res(re*op2.re - im*op2.im, re*op2.im + im*op2.re);
return res;
}
Complex operator/(Complex op2)
{
double dvs = op2.re*op2.re+op2.im*op2.im;
Complex res((re*op2.re + im*op2.im)/dvs,
(im*op2.re - re*op2.im)/dvs);
return res;
}
};

, operator
() ++. operator
+
,
:

a = b.operator+(c);
, , -
:

a = b + c;
22

, , ,
:

Complex c1(2.7, 3.8);


Complex c2(1.15, -7.1);
double mod = (c1+c2).modulo();
, ++
, , , .
, :
(a ? b : c) (). ,
() ,
. .

2.3.
, ++, , .
++

,
/ . , :

void print(int n) { printf("%d\n", n); }


void print(const char *s) { printf("%s\n", s); }
void print() { printf("Hello world\n"); }
,
,
. :

print(50);
// print(int)
print("Have a nice day"); // print(const char*)
print();
//
.
.
,
. ,
:
23

void f(const char *str)


{
printf(" : %s\n", str);
}
void f(float f)
{
printf(" : %f\n", f);
}
f("string") f(2.5), . , f(1) ,
float, const char *. f(0) , . .
0
const char*, float. , f (!),
f(0) .

2.4. .

Complex, (. . 16),
Complex
, . . Complex
. , :

Complex sum; // -
sum = c1+c2;
, ; , , ; , ,

,
.
. , -
( ), (
). ++
24

; , , . ,
, (  ), / . ,
Complex :

class Complex {
double re, im;
public:
Complex(double a_re, double a_im)
{ re = a_re; im = a_im; }
Complex() { re = 0; im = 0; }
//....
Complex, . , , .
, , :

Complex z3; //
Complex v[50]; // 50
// ..

2.5.
, , ,
.
 ( ) .
. , a , b float,
a + b,

a float, . ,
void f(float),
f(25), , . . ,
;
,
int float.
, ++
, , ,
25

, -

. .

++, , A B 
, B A. ,
float,
int; , , .
2.1.3, ++ . ,
B , A,
B
A.
.
, , ,
, ,
4 ,
.

Complex. , ,
.
, :

Complex(double a) { re = a; im = 0; }
, , :

Complex c(9.7);
,

void f(Complex a);


:

f(2.7);
4

explicit

26

Complex ;

Complex, f.

2.6.

. , , .
,

.
++  ,
,
, . , ,
. , * &5 .
:

int i;
//
int *p = &i; // i
int &r = i; // i
i++;
(*p)++;
r++;

// i 1
//
//

, , . .
:  ,
, , . , i,

i  r,
.
(
).

5 , & ! ++ .
 .

27

++
. ,
6 . , , oat.
:

void max_min(float *arr, int len, float *min, float *max)


{
int i;
*min = arr[0];
*max = arr[0];
for(i=1; i<len; i++) {
if(*min>arr[i]) *min = arr[i];
if(*max<arr[i]) *max = arr[i];
}
}
 , :

float a[500];
float min, max;
// ...
max_min(a, 500, &min, &max);
, . ,

,
, , ;
(&).

, . . min
max *, . ,
:

void max_min(float *arr, int len, float &min, float &max)


{
int i;
min = arr[0];
max = arr[0];
6 , , :
- (var-parameters).

28

for(i=1; i<len; i++) {


if(min>arr[i]) min = arr[i];
if(max<arr[i]) max = arr[i];
}

}
// ...
float min, max;
max_min(a, 500, min, max);

, min max, ,
, , min max,
, .
, ( )
, .
. , (,
, , , . .),
, . ,
.

int &find_var(/*params*/);
, , :

int x = find_var(/*...*/) + 5;
find_var(/*...*/) = 3;
find_var(/*...*/) *= 10;
find_var(/*...*/)++;
int y = ++find_var(/*...*/);

2.7. const
, , const, ++,
. , , .
const 
. ,
29

, (
, ).
, , .
,
.

. ,
:

#define MAX_LINE_LENGTH 130


const , :

const int max_line_length = 130;


, , . c, 15.
:

#define c 15
,
c , , :

void f(int i)
{
int c;
// ...
}
int c int 15 , , .
, , ,

c.
c :

const int c = 15;


, . . c,
f(),
.
30

, , /++
.
const , , /
, . :

const char *p;


// p
p = "A string";
// , p
*p = 'a';
// ! ,
// p
p[5] = 'b';
//
, const char *p  , . -

, :

char buf[20];
char * const p = buf+5;
// p - -,
// buf (buf[5])
p++;
// , p
*p = 'a';
// , buf[5]
p[5] = 'b'; // , buf[5+5]
:

int i;
const int &r = i; //
int x = r+5; //
i = 7;
//
r = 12; // , r
const int j = 5;
int &jr = j; // ,
//
const int &jcr = j; //
,
,
31

, . ,
, . , Complex

Complex operator+(Complex op2)


{ return Complex(re+op2.re, im+op2.im); }

Complex operator+(const Complex &op2)


{ return Complex(re+op2.re, im+op2.im); }
, ( )
double
.

2.8.
const ,

, class struct, .
, , . ,
, ( )
, .
. ,
, .
++ . ,
( ) const:

class C1 {
// ...
void method(int a, int b) const
{ /* .... */ }
// ...
};
, ,
,
,
,
32

. . , , (
).
, . , :

void f(const Myclass *p) {


p->my_method();
}
, Myclass
my_method() .
,

, , , ,
. ,

Complex , , . Complex
,
const:

class Complex {
double re, im;
public:
Complex(double a_re, double a_im)
{ re = a_re; im = a_im; }
Complex(double a_re)
{ re = a_re; im = 0; }
Complex() { re = 0; im = 0; }
double modulo() const
{ return sqrt(re*re + im*im); }
double argument() const
{ return atan2(im, re); }
double get_re() const { return re; }
double get_im() const { return im; }
Complex operator+(const Complex &op2) const
{ return Complex(re+op2.re, im+op2.im); }
// ...
};
, (
) , . : ,
.
33

2.9.

,
() , ++ ,
.
, (, ), , . .
( ,
). , ,
.
-.  ,
, . - ,
( ), ~ (). -
, . . .
,
( ).
File, .

class File {
int fd; // . -1 ,
public:
File() { fd = -1; }
//
bool OpenRO(const char *name) {
fd = open(name, O_RDONLY);
return (fd != -1);
}
// ,
// true ,
// false
// ...
// ... ...
// ...
~File() { if(fd!=-1) close(fd); }
34

};

// ,

, File
. , , ( return) .
,

, .

2.10.

,
;
malloc(), realloc() free(). ++
, ,
,
/ , , . ,
, , . malloc() free()
, , . ,
,
++ .
++

.
( ) ++ new, . :

int *p;
p = new int;
, ,
, . ,
35

Complex (. 2.1.5)
:

Complex *p;
p = new Complex(2.4, 7.12);
delete:

delete p;
new delete,
:

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


delete [] p;
//
,
.
, new
,
(. 2.4).
, , new, delete . ,

,
, , .
delete ,
malloc(), , ,
new, free(). .

2.11.
.
( Cls1) ,
; ,
.

class Cls1 {
int *p;
public:
36

};

Cls1() { p = new int[20]; }


~Cls1() { delete [] p; }
// ...

, -
Cls1. , ,

. :

void f(Cls1 x) {
// ...
}
int main() {
// ...
Cls1 c;
f(c);
//...
}

f(). x c.
, . ,
Cls1
;
, ,
: c
x. . 2.1.

...
p

. 2.1.

(, f() x,
c, ),
f() (
x), , c
,
.
37

c,
, (
).
,
,
Cls1. ++
,
.
 ,
,
() ; const, ,
. ,
, , ,
, . Cls1:

class Cls1 {
int *p;
public:
Cls1() { p = new int[20]; }
Cls1(const Cls1& a) {
p = new int[20];
for(int i=0; i<20; i++) p[i] = a.p[i];
}
~Cls1() { delete [] p; }
// ...
};
f() , . 2.2.
C

...
p

...

. 2.2.
38

2.12.

(. 2.1.3, . 16; 2.5, . 27). , ,
; , ,

. ,
(, ). , ,
t z Complex t z,
. :

Complex imag_1(0, 1);


t = z * imag_1;
, :

t = z * Complex(0, 1);
.
;
, ,
, .

. , . 26
f, Complex,
, ;
,
Complex,
f.
. a, b c, Complex,
, , :

t = a + b + c;
, ,
, , , ,
Complex,
Complex. , a b ,
, c . ,
39

. , ,
 ,
,
( , , ).
operator+().
,
;
7 .
: , ,
; , . :
, ,
.
, ,
,
.
:
,

, ,
.
.
, -,
, ,

, ,
.
, , .

: const , . , , ,
(,
).
7 ,
, .

40

2.13.
2.13.1.

++ (. .
, ) ,

.
. , :

void f(int a = 3, const char *b = "string", int c = 5);


:

f(5, "name", 10);


f(5, "name"); // , f(5, "name", 5);
f(5);
// , f(5, "string", 5);
f();
// , f(3, "string", 5);
.
,

, , ,
. ,
:

void f(int a = 0, int b = 10, int c = 20);


void f(int a, int b = 10, int c = 20);
void f(int a, int b, int c = 20);
 :

void f(int a = 0, int b, int c = 20);


void f(int a = 0, int b = 0, int c);
void f(int a = 0, int b, int c);
// b c , .. a
void f(int a, int b = 10, int c);
// c , .. b
,
. n , n
. ,
41

int f(int a, const char *str = "name", int *p = 0);


:

int x;
f(5, &x);
&x int *,
f,
const char *.
, , ,
.

, , ;
, .

2.13.2.
2.4, 2.5 2.11
, , :

, , ,
;

, ,
.

,
, ,
. , ,
Complex , , ,
:

Complex(double a_re = 0, double a_im = 0)


{ re = a_re; im = a_im; }
,
( ),
double ( double).
42

2.14.
++ , ( ) ,
.
: ++ , ,
, . ,
++ , , .
.
 , ,
, .
++ :
( )
. -

, , -

, (
) . : ,
,
,  .
: -

,
. -

(),
, ,
. , 2.1.3,
str_complex , ,
,
( , ) .
. ,

. , , :
, .
, 43

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

2.15. .

-
. , ,
, , ,
8 .
,
( )
. ,
, ,
. , () .
,
;
,
,
,
.
,
. , , . ++ : ,

#include "..." .
8 , , , - . , , . ,
( ) 25
- . . ,
,
. .

44

,
, , ,
. , : ( !)
, .
( )
( ).
() , , , () const, , .
- , , , (
, ;
).
- , , .
, ++
:: ( ). , C1
f() g(),
:

class C1 {
// ...
public:
C1();
void f(int a, int b);
int g(const char *str) const;
};
// ... //
C1::C1()
{
//
}
45

void C1::f(int a, int b)


{
// f
}
int C1::g(const char *str) const
{
// g
}

. ,
, f, f ,
; f f(), . , f
 , . ,
, , ,
(,
), ,
;
.
, ( ) . , .
, , ,
, , ; , . .
, C1 (
) f,  C1::f.
,
.
.

2.16.

.
; ,
46

, , , ,
.
. A  ,
int:

class A {
// ...
public:
A(int x, int y) { /*...*/ }
// ...
};
B, A. , B
( ):

class B {
A a;
public:
B();
// ...
};
B(). (
) a, , ,
A.
A ! ?
, ++
. ( ) ,
. :

B::B() : a(2, 3) { /*...*/ }


, a () (2 3). , A
B.
, ,
. , Complex
:
47

class Complex {
double re, im;
public:
Complex(double a_re, double a_im) : re(a_re), im(a_im) {}
Complex(double a_re) : re(a_re), im(0) {}
Complex() : re(0), im(0) {}
// ...
.
( ) , . , ,
, .

2.17.

Complex -.
, ,
:

Complex z, t;
// ...
z = t + 0.5;
( 0.5 Complex ). ,
:

z = 0.5 + t; // !
, operator+
Complex, 0.5 . , , ,
.
. ,
( ,
, ),
, . , operator+ Complex,
:

Complex operator+(const Complex& a, const Complex& b)


48

{
}

return Complex(a.get_re() + b.get_re(),


a.get_im() + b.get_im());

Complex z, t;
// ...
z = t + 0.5;
z = 0.5 + t;
.
( )
,
, ; , ,
,
( , OpenSource,
).

2.18.
, . ++ , ,
(friend);
.
;
, . ,
A , B ,
B A.

. 2.1.4,
 ; , .
, 
,
. , operator+
49

Complex::get_re() Complex::get_im(), , Complex,


re im . ( ) , ;
, .

. Complex
friend, operator+ .
,
friend:
class Complex {
friend Complex operator+(const Complex&, const Complex&);
//...
operator+,
( get_re()
get_im()):

Complex operator+(const Complex& a, const Complex& b)


{
return Complex(a.re + b.re, a.im + b.im);
}
, . 49.
, :

class Cls1 {
friend void f(int, const char *);
//...
};
void f(int, const char *)
{
// Cls1
}
, friend class
:

class A {
friend class B;
//...
};
50

, , , , ; , friend. 
,
,
, ,
: ,
- ,
, friend
. , ,
.

2.19.

2.19.1.

, ++ , , .
, a = -

, , , ,
.
, ,
+=, -=, <<=, |= . ,
, . , , :

, .
, , ,
. , ( )
, . , ,
: ++ . , ,
void, . , Complex :

class Complex {
// ...
const Complex& operator=(const Complex& c)
51

};

{ re = c.re; im = c.im; return *this; }


const Complex& operator+=(const Complex& c)
{ re += c.re; im += c.im; return *this; }
// ...

, ,
:

class Complex {
// ...
void operator=(const Complex& c)
{ re = c.re; im = c.im; }
void operator+=(const Complex& c)
{ re += c.re; im += c.im; }
// ...
};
, .
+=, -=
++ , , , += =, +.
= +, +=,
.
,
. , ,
, :

class Complex {
// ...
void operator=(double x) { re = x; im = 0; }
// ...
};
,
( , ),
: ,

, . , ,
, ++. , - ,

:
52

class A {
// ...
private:
void operator=(const A& ref) {} // no assignments
};
2.19.2.
, , ,
; a[b]
*(a+b), . ++ ,
, ,
. , , ,
.
, , ()
.
, .
16 ,
,
.
, (
2.11).
,
.

.
:
class IntArray {
int *p;
//
unsigned int size; //
public:
IntArray() {
size = 16;
p = new int[size];

53

}
~IntArray() { delete[] p; }
int& operator[](unsigned int idx);
private:
void Resize(unsigned int required_index);
//
void operator=(const IntArray& ref) {}
IntArray(const IntArray& ref) {}
};

, . ,
, .
Resize(),
. , , (
),
.
, , . operator[]()
, ,
. :
int& IntArray::operator[](unsigned int idx) {
if(idx >= size)
Resize(idx);
return p[idx];
}

Resize():
void IntArray::Resize(unsigned int required_index) {
unsigned int new_size = size;
while(new_size <= required_index)
new_size *= 2;
int *new_array = new int[new_size];
for(unsigned int i = 0; i < size; i++)
new_array[i] = p[i];
delete[] p;
p = new_array;
size = new_size;
}

54

, , :

IntArray arr;
arr[500] = 15;
arr[1000] = 30;
arr[10] = arr[500] + 1;
arr[10]++;
,
, , .
, .
, ,
( ). ,
, , ,
.

2.19.3. ++ - ++ --, . (
, / ), , : (++i)
(i++). ,
.
, ++ .
, . , , operator++() operator--()
(, ++i); , ()
( ), operator++ (operator--)

.
, operator++ (operator--),
() int.
; , , . , 55
,

()
/
operator++ (operator--)
(), ,
(
). . A
:

class A {
public:
void operator++() { printf("first\n"); }
void operator--() { printf("second\n"); }
void operator++(int) { printf("third\n"); }
void operator--(int) { printf("fourth\n"); }
};
:

A a;
++a;
a++;
--a;
a--;

//
//
//
//

first
third
second
fourth

( )
first, third, second fourth, .
;
,
.

,
, , ( ) .
:

,
.
, operator++(int)
() , ,
,
,
: ,
, .
,
:

class MyInt {
56

int i;
public:
MyInt(int x) : i(x) {}
const MyInt& operator++() { i++; return *this; }
MyInt operator++(int)
{ MyInt tmp(*this); i++; return tmp; }
// ...
,
, ( tmp )
. ++
-- .

2.19.4. ->
, ->. ,
, . ++ ; ,
, ,
. ,
, , .
. ->,
,
,
(). ,

struct s1 {
int a, b;
};
:

s1 *p = new s1;
a : p->a.
, p a; a 
, , ,
! , a , . ,
, . ,
p->a , p. , a, p
57

, s1*
( s1). ,
, ->a ( a).
, , -> . , ,
;
.
->. , ->
,
. , ++
, : -> operator->(), (
),
, (
), , , -> . -> operator->(),

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

class Pointer_s1 {
s1 *p;
public:
,
s1 ,
; , . :

Pointer_s1(s1 *ptr = 0) { p = ptr; }


~Pointer_s1() { if(p) delete p; }
:

s1* operator=(s1 *ptr) {


if(p) delete p;
58

p = ptr;

, Pointer_s1
, s1
. Pointer_s1,

:

private:
Pointer_s1(const Pointer_s1&) {}
// copying prohibited
void operator=(const Pointer_s1&) {}
// assignments prohibited
, ,
s1, , ( *)
(->), :

public:
s1& operator*() { return *p; }
s1* operator->() { return p; }
};
, , . ,
Pointer_s1,
s1,
,
, s1:

int f() {
Pointer_s1 p;
p = new s1;
p->a = 25;
p->b = p->a + 36;
// ...
// f
}
2.19.5.
,
, (, ), , , . , , ,
59

operator ; ,
. , :

void operator()() { /* */ }
, .
. Fun,
, :

class Fun {
public:
void operator()()
{ printf("fun0\n"); }
void operator()(int a)
{ printf("fun1: %d\n", a); }
void operator()(int a, int b)
{ printf("fun2: %d %d\n", a, b); }
};
:

Fun f;
f(); f(100); f(25, 36);
:

fun0
fun1: 100
fun2: 25 36
2.19.6.

int i;
double d;
// ...
i = d;
, , () int double.
60
,

, .  (. 2.11).
. , , , . , -
, . ( ) ,
,
, ()
.
.
,
operator , .
, . :

class A {
//...
public:
//...
operator int() { /* ... */ }
};
A int ,
, :

A a;
int x;
// ...
x = a;
, .
, , , ,

, .

;
(, operator), . 61

,
, 2.20.

2.20. :

(, ), ( ) , , . ,
, ( , ).
++ , 9 ,
( ), , . SparseArrayInt.
, , .
/.
, , , .
.

. , ,
,
- SparseArrayInt, operator[]. (
2.19.2), , ,
. , .
( ) ,
, , , .
, ,
, 9 unsigned long;
232 1, . . .

62

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

.
,
- ,
.
,
;
, ; , ,
, .
, ++ , ,
10 . , ,

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

10 ++,
.

63

,
. , , , int ,
:

SparseArrayInt
int x;
//...
x = arr[500];
arr[300] = 50;
arr[200] = 0;

arr;
//
// ( )
// ,

, . ,
 , .
, , :

arr[15] += 100;
x = arr[200]++;
y = --arr[200];
, ,
: ++ , (+=,
-=, <<= . .), /
(++ -- ).
+= ++.
.
SparseArrayInt,
,

. Provide , , ,
; ,
. , Remove,
, . Interm
.
:

intermediate

class SparseArrayInt {
struct Item {
int index;

64

int value;
Item *next;

};
Item *first;
public:
SparseArrayInt() : first(0) {}
~SparseArrayInt();
class Interm {
friend class SparseArrayInt;
SparseArrayInt *master;
int index;
Interm(SparseArrayInt *a_master, int ind)
: master(a_master), index(ind) {}
int& Provide(int idx);
void Remove(int idx);
public:
operator int();
int operator=(int x);
int operator+=(int x);
int operator++();
int operator++(int);
};
friend class Interm;
Interm operator[](int idx)
{ return Interm(this, idx); }
private:
SparseArrayInt(const SparseArrayInt&) {}
void operator=(const SparseArrayInt&) {}
};

SparseArrayInt, ,
: .
, ,
. 
. :

SparseArrayInt::~SparseArrayInt() {
while(first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
65

SparseArray::Interm, :
int SparseArrayInt::Interm::operator=(int x)
{
if(x == 0) {
Remove(index);
} else {
Provide(index) = x;
}
return x;
}
int SparseArrayInt::Interm::operator+=(int x)
{
int& location = Provide(index);
location += x;
int res = location;
if(res == 0) Remove(index);
return res;
}
int SparseArrayInt::Interm::operator++()
{
int& location = Provide(index);
int res = ++location;
if(location == 0) Remove(index);
return res;
}
int SparseArrayInt::Interm::operator++(int)
{
int& location = Provide(index);
int res = location++;
if(location == 0) Remove(index);
return res;
}
SparseArrayInt::Interm::operator int()
{
Item* tmp;
for(tmp = master->first; tmp; tmp = tmp->next) {
if(tmp->index == index) {
return tmp->value;
}
}
return 0;
}

, Provide Remove:
int& SparseArrayInt::Interm::Provide(int idx)

66

Item* tmp;
for(tmp = master->first; tmp; tmp = tmp->next) {
if(tmp->index == index)
return tmp->value;
}
tmp = new Item;
tmp->index = index;
tmp->next = master->first;
master->first = tmp;
return tmp->value;

}
void SparseArrayInt::Interm::Remove(int idx)
{
Item** tmp;
for(tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
{
if((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
}

2.21.
, , , /
, , , ,
. ++ static11 .

2.21.1.

, , , 11 , ,
; , ++
static, .

67

; , , . ,
, :
, ::12 ; , , ,
,
.
:  , ,
; , , . ,
, ,

.
, , static:

class Cls {
//...
static int the_static_field;
//...
};
, , :
,
, ,
.

, , extern. , ,
, , ,
,  .
, ,

:
int A::the_static_field = 0;

,
, .
, , , ,
!
12

2.15 . 45.
68

,

, A
.
,
.
. ,
,
:

A a;
a.the_static_field = 15; //
A::the_static_field = 15; //

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

2.21.2.
 -, ,
, . ,
. ,
static, :
69

class Cls {
//...
static int TheStaticMethod(int a, int b);
//...
};
, ,
, , :

Cls::TheStaticMethod(5, 15); //
Cls c;
c.TheStaticMethod(5, 15); //
- , , , this (.
2.1.2). , ,
, , , . -
,
.
, - .
: , ;
; ,
.
,
,
. ,

, () (,

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

70

3.

3.1.


,
. , , , , ; , , ,
; , , ,
, , , . .
, , , .
, , ,  ;
, ,
, .
,
,
, .
.
. : ,
, ,
, , ? ,
71

: - ( "ERROR") , ,
exit(). , , . , ,
- ,
, , .
-,
,
. , .
, . ,
MS Windows ,
. Unix
, ,
; ,
- ,
.
, . , ,
:
.
, , -1 .
, , ,
( , , , ).
, , ,
,  . , ,

; .
: , -

 . ,

1 (DNS),
 , .

72

main() , .
, ,  ,
.
, ,
, , . ,
, , , ,
, , . ,
, . . , f1() f2(), ,
, f3() . ., , , f10()
. , , f9() , , ,
.
, . .,
,
,  (1) (2)
, - , .
: ,
, . ,
. , ,
, ,
,
, .
. ++ (. exception
handling ).

3.2.
.
;  atoi(),
73

int.
, , int,
, ( - ) , , int.
, , atoi , , - (,
, ). ,
, , ,
, , , "0", .
,
: , ,
, ,
, ,
.

,
- , - . , ; call/cc, ,
; Common Lisp, call/cc, ,
, , ++.
, , ,
, ,
.
, , , : f1() f2(), ,
, f3() . . f10(), . -
f9, f8 . ., , , f1 .
f10 , f9, f8,
f1, . ,
g() h(), , g() , ,
g() ,
h().
main().
, 74

2 , , ,
.

3.3.
, ,
throw (.
).
, , , ,
(int, float, ...), ( . .), ( , ,
). throw
,  .
,
() , (. . ) . , ,
;
(, -1), , . ++
:

unsigned int line_count_in_file(const char *file_name)


{
FILE *f = fopen(file_name, "r");
if(!f)
throw "couldn't open the file";
int n = 0;
int c = 0;
while((c = fgetc(f)) != EOF)
if(c == '\n') n++;
fclose(f);
return n;
}
(, , . . const char*).
; , int:

throw 27;

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

75

, , ; .

3.4.
, , ,
. ,
, ,
(, main).
. , , , .
, .
, -

, ,

. .

++ try (.
), , ,
. try- . , ; ,
catch (.
),
,  ( , ). ,
.
, ,
. , line_count_in_file
,
.

#include <stdio.h>
unsigned int line_count_in_file(const char *file_name);
76

int main(int argc, char **argv) {


if(argc<2) {
fprintf(stderr, "No file name\n");
return 1;
}
try {
int res = line_count_in_file(argv[1]);
printf("The file %s contains %d lines\n",
argv[1], res);
}
catch(const char *exception) {
fprintf(stderr, "Exception (string): %s\n",
exception);
return 1;
}
return 0;
}
, ,
; ,
line_count_in_file
, main.
line_count_in_file, try-
, (catch-).
, try-, : ,
line_count_in_file, . . .
,
const char *, char *, ( char) ++  , . const, .

, ++ (
). try-

, - :

try {
// ...
}
catch(const char *x) {
// ...
77

}
catch(int x) {
// ...
}
:

(catch-) ,

,
, . , ,

, 3 ,
.

, try-. , ,
.
,

, ,
,
try-. ,

try-,
( ,
 ), .
,
try- .
throw,  .
, . , ,
, - .
.

3.5.
,
.

3
, ;
.

78

, ,
. , ,
. ,
, ,
, ,
,
main try-:

int main() {
try {
//
return 0;
}
catch(const char *x) {
fprintf(stderr, "Exception (string): %s\n", x);
}
catch(int x) {
fprintf(stderr, "Exception (int): %d\n", x);
}
catch(...) {
fprintf(stderr, "Something strange caught\n");
}
return 1;
}
throw
. throw
, - , .
,
( , . .)
, . ,
:

void f(int n) {
int *p = new int[n];
//
delete[] p;
}
, new delete, , delete ,
p, ( ).
79

, try-, , ,
, :

void f(int n) {
int *p = new int[n];
try {
//
}
catch(...) {
delete[] p;
throw;
}
delete[] p;
}

3.6.
. . , couldn't open the le,
, errno fopen,
. , ,
, ,

,
.
, . , ; ,
.

. ,

.

, 
, . ,
80

,
; , , . ,
, ,
.
, , .
. ,
. , ,
; , , , , throw, ,
, . , -

, .

, line_count_in_file().
, (
,
) errno
. strdup4 ;
, static.

class FileException {
char *filename;
char *comment;
int err_code;
public:
FileException(const char *fn, const char *cmt);
FileException(const FileException& other);
~FileException();
const char *GetName() const { return filename; }
const char *GetComment() const { return comment; }
int GetErrno() const { return err_code; }
private:
static char *strdup(const char *str);
};
4
, new[], malloc().

81

, strdup
:

FileException::FileException(const char *fn, const char *cmt)


{
filename = strdup(fn);
comment = strdup(cmt);
err_code = errno;
}
FileException::FileException(const FileException& other) {
filename = strdup(other.filename);
comment = strdup(other.comment);
err_code = other.err_code;
}
FileException::~FileException() {
delete[] filename;
delete[] comment;
}
char* FileException::strdup(const char *str) {
char *res = new[strlen(str)+1];
strcpy(res, str);
return res;
}
line_count_in_file
(. . 75) :

unsigned int line_count_in_file(const char *file_name)


{
FILE *f = fopen(file_name, "r");
if(!f)
throw FileException(file_name,
"couldn't open for line counting");
// ...
, (catch-)
, , :

catch(const FileException &ex) {


fprintf(stderr, "File exception: %s (%s): %s\n",
ex.GetName(), ex.GetComment(),
strerror(ex.GetErrno()));
return 1;
}
82

3.7.
, . 80, ,
. , .
, -

, , (
), ,
, .

, , A, ,

void f() {
A a;
//..
g();
//..
}
f() a
, , g()
f().
++ .

3.8.

, (catch-),
,
throw, , .
,
, , , int char
long.
. , ,
throw A, catch- catch(A &ref). ,
, , , char*,
char*, const char*.
83

, , char * ( const) const char*, , , , ,


:

throw "I can't work";


(, , )
.
.

84

4.

4.1.
, - , ,
,
. ., , , . , , , ,

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

. , , -, , , , ,
.
,
 , ,
. ,
, , . ,
, ,
85

, ,
.
, , , , , ,
, , . .
, ; . , . -
, .

4.2.

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

struct person {
char name[64];
char sex; // 'm' or 'f'
int year_of_birth;
};

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

struct student : person {


int code;
86

};

int year; //
float average;

student, person :

student s1;
strcpy(s1.name, "John Doe");
s1.sex = 'm';
s1.year_of_birth = 1989;
s1.code = 51311;
s1.year = 2;
s1.average = 4.75;
person , student  ,
.
( , , person student).

student

sex

person

name

year_of_birth
code
year
average

. 4.1.
s1 . 4.1.
, ,
student, person, (
),
person. , s1 ,
87

person, student ( , :
person , student).
++
student person, ,
, - . , . , ,
:
student s1;
person *p;
p = &s1;
person &ref = s1;
,
person, -
, , student:

void f(person &pers) { ... }


// ...
student s1;
// ...
f(s1); // !
, -

,
. ,
( s1 student, person),
( f() person,
, student).
4.3. ;

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

,
, ;
this (. 2.1.2). , ,
,
,
,
.
,
,
, . , . 4.1,
.
, , , :  ( ),
 ( ).
. , ,
, ,
.
. ,
,  . , ,
, . , , ,
 . , -
- ,
.
: ,  .
( , ), ,
( ) . , (. 2.16).
89

:
,
( ) . , A  , int, B  , A, int i,
: .

B::B() : A(2, 3), i(4) { /* ... */ }


2 3  , 4 
i.

4.4.
. , ,
, .
++ (public)
(private).
, :

class B : public A { /*...*/ };

class C : private A { /*...*/ };


A (
, ) B ,  C,
, C A.
,
. 86. :
(public), 
(private). , public,
, .
,
,
, .
90

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

4.5.
- , . , ,
, ,
.
, , , , ( ) ,
, , ,
, . .
,
 .
, ( ) ( ). , , 
91

(
Show()), (Hide()) (Move()).

class Pixel {
double x, y;
int color;
public:
Pixel(double ax, double ay, int acolor)
: x(ax), y(ay), color(acolor) {}
void Show();
void Hide();
void Move(double nx, double ny);
};
Show() Hide() , . .;
, , - . ,
Move(). , , , , ,
:

void Pixel::Move(double nx, double ny)


{
Hide();
x = nx;
y = ny;
Show();
}
, .
, (
) , , .
Pixel 1 ,
Circle
. , Circle , ,
. ( ) :
(protected), ;
Pixel protected:

1 - , , , .
.

92

class Pixel {
protected:
double x;
//...
Circle , , :

class Circle : public Pixel {


double radius;
public:
Circle. , Pixel.
, , , . 90. :

Circle(double x, double y, double rad, int color)


: Pixel(x, y, color), radius(rad) {}
, Show() Hide(),
. , , ; , Pixel,
, :

void Show();
void Hide();
,
Move(), ,
Pixel. . ,
Move()
,
, ,
, ! ,

, : , , .
,
Circle Move(),
Pixel, Circle.
93

, ( )
Move() Circle, ,
( , ),
, . Pixel::Move()
Pixel, Show()
Hide(). , ,
Pixel::Move() Pixel::Show()
Pixel::Hide(), CALL , .
Move() Circle,
Hide()
, Pixel. -,
.
Show():
. , , .
,
Circle , ,
. . ,
( )  ,
, ,
-, , , , .
, ,
:

, -;
- ;

, -.
++
- ( ). virtual. , , , , ,
,
94

. , Pixel virtual Show() Hide(),


Move() , ,
this,
Pixel, - -,

Show() Hide(), . , , ,
, , .

, .
, , (. virtual method table pointer, vmtp).
( ) ,
. , ,
vmtp,
, , , .
- , , , -.
vmtp, -
, -. -
(- )
, ; vmtp.

, Show() Hide()
. Move() , Pixel,
( ) Show() Hide().
Pixel Circle, ,
, ,
. , . , .
:
class Pixel {
protected:
double x, y;
int color;
public:
Pixel(double ax, double ay, int acolor)
: x(ax), y(ay), color(acolor) {}
virtual ~Pixel() {}

95

};

virtual void Show();


virtual void Hide();
void Move(double nx, double ny);

class Circle : public Pixel {


double radius;
public:
Circle(double x, double y, double rad, int color)
: Pixel(x, y, color), radius(rad) {}
virtual ~Circle() {}
virtual void Show();
virtual void Hide();
};

, Circle virtual , , ; , , .

4.6. .

. 92, - , . . ,
, 
,
,

.
,
. ; , -
, , . .
,
: ,
, .
, Move()
. 92.
, , - .
,
96

. ,

Pixel Circle, .
, , .
,
Show() Hide(), ,
(
, . .). , Show() Hide()

; , ,
, ?!

, ,
Move() , -
Show() Hide(). , , - ,
, .
( )
,
.
++ ,
.
(.
).
, ,
-,
, ( ) , .
:

pure virtual functions

class A {
// ...
virtual void f() = 0;
// ...
};
97

= 0;, 2 .
, , ,
, , , , ,
,
.
, , . , .

,
.
.
- ,
, , ,
; GraphObject. Pixel
Circle , GraphObject.
GraphObject Show() Hide() , .
GraphObject:

class GraphObject {
protected:
double x, y;
int color;
public:
GraphObject(double ax, double ay, int acolor)
: x(ax), y(ay), color(acolor) {}
virtual ~GraphObject() {}
virtual void Show() = 0;
virtual void Hide() = 0;
void Move(double nx, double ny);
};
Move() , Pixel::Move() . 92. ,
Move() Show() Hide(). ,
2 , , , , ; ,
++.

98

, ,
-,
, , -.
Pixel Circle :

class Pixel : public GraphObject {


public:
Pixel(double x, double y, int col)
: GraphObject(x, y, col) {}
virtual ~Pixel() {}
virtual void Show();
virtual void Hide();
};
class Circle : public GraphObject {
double radius;
public:
Circle(double x, double y, double rad, int color)
: GraphObject(x, y, color), radius(rad) {}
virtual ~Circle() {}
virtual void Show();
virtual void Hide();
};
, GraphObject,
Show() Hide().

4.7.

, -
,
, . ,
.
, -
GraphObject, ,
.
, ; ,
99

. , . , ,
,
AddVertex()3 . :

class PolygonalChain : public GraphObject {


struct Vertex {
double dx, dy;
Vertex *next;
};
Vertex *first;
public:
PolygonalChain(double x, double y, int color)
: GraphObject(x, y, color), first(0) {}
virtual ~PolygonalChain();
void AddVertex(double adx, double ady);
virtual void Show();
virtual void Hide();
};
AddVertex() ( )
, ; , , ,
:

void PolygonalChain::AddVertex(double ax, double ay) {


Vertex *tmp = new Vertex;
tmp->dx = ax;
tmp->dy = ay;
tmp->next = first;
first = tmp;
}
, , , , . :

PolygonalChain::~PolygonalChain() {
while(first) {
Vertex *tmp = first;
3 ,
, , ,
, ( ),
.

100

first = first->next;
delete tmp;

, Show() Hide(),
, .
,
, . ,
, PolygonalChain.
,
a, ( (0, 0)),
(a, 0), (a, a), (0, a) (0, 0); , ,
,
, .
( PolygonalChain,
), (
Square), PolygonalChain, :

class Square : public PolygonalChain {


public:
Square(double x, double y, double a, int color)
: PolygonalChain(x, y, color)
{
AddVertex(0, 0);
AddVertex(0, a);
AddVertex(a, a);
AddVertex(a, 0);
AddVertex(0, 0);
}
};
, , .

4.8.
. 95 ,
, ,
101

() ,
. .
, delete ,
,
. , ,
, , . , , GraphObject:

GraphObject *ptr;
:

ptr = new Square(27.3, 37.7, 0xff0000, 10.0);


GraphObject,
Square.
,

delete ptr;
GraphObject*,
GraphObject ,
. Square, PolygonalChain, , ,
GraphObject.
GraphObject ,
, GraphObject. ,
Square (
), PolygonalChain ,
, - , .

:
,
( !). ,
, . ,
,
delete, , . ,
, . ,
102

, , , , ;
, .

4.9.
.
4 ,  , , , , -
, ,
GraphObject. , ; ,
(, ),
(, ,
-).
, , .

GraphObject. , , scene_length,
scene:

int scene_length;
GraphObject **scene;
scene_lenght (, ),
:

scene = new GraphObject*[scene_length];


, ,
( , , i
scene_length):

scene[i] = new Pixel(1.25, 15.75, 0xff0000);


// ...
scene[i] = new Circle(20.9, 7.25, 0x005500, 3.5);
// ...
scene[i] = new Square(55.0, 30.5, 0x008080, 10.0);
// ...

4 , , .

103

. ,
GraphObject*,
. ,
,
.
, ,
, Show(), Hide() Move()
GraphObject, , GraphObject* .
, :

for(int i=0; i<scene_length; i++) delete scene[i];


delete [] scene;
- . , , , ; ,
, .

4.10.
.

, A B,

,
(, x). -
( ),
- ,
++: x -


, 5 .

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

104

x, x,  ++
. :

class A { // ...
public:
void f(int a, int b);
};
class B : public A {
double f; // f(int, int)
};
B, f :

B b;
b.f(2, 3);

// !!! f

; B - f, A,
:

b.A::f(2, 3);

//


, - , , ,
.
:

class A { // ...
public:
void f(int a, int b);
};
class B : public A {
public:
double f(const char *str); // f(int, int)
};
B b;
double t = b.f("abrakadabra"); //
b.f(2, 3);
// !!!
b.A::f(2, 3);
//
105

4.11. -

 ,
 .

. .
.

, - .
,
, :
,  , ,
( , , Smalltalk).

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

, , , . , . ,

(A B ). (. subclass )
(. superclass )  .
.
, (
) ,
( 
), (
),
, . .
. ,
,
,
: 106

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

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

, ,
, , , , :

char *p = (char*)malloc(100);
malloc(100), void*,
char*.

,
,
, , , .
, , .
,
++
, . : , (static_cast, dynamic_cast, const_cast reinterpret_cast),
, ,
107

, , :

Square *sp = static_cast<Square*>(scene[i]);


, , ++ . , const_cast
, , const6 ;
:

int *p;
const int *q;
const char *s;
// ...
q = p; //
p = q; // ! const
p = const_cast<int*>(q); //
p = const_cast<int*>(s); // !
, const_cast .
; , , , , , const -,
, . . const_cast

,
. -

const_cast
.
static_cast
, , . .
. . :

class A { /* ... */ };
class B : public A { /* ... */ };
class C { /* ... */ };
A *ap;
B *bp;
C *cp;
6 volatile,
.

108

//
ap
bp
bp
cp

...
= bp; //
= ap; // !
= static_cast<B*>(ap); //
= static_cast<C*>(ap); // !

, , ,

, ;
.
reinterpret_cast ( ), ,
( ,
, , ).
, , .
, , reinterpret_cast, , ,
reinterpret_cast
, .
dynamic_cast. , ,
, . . ,
, 7 .
dynamic_cast, ,
.
static_cast, dynamic_cast
, , . . . static_cast : ,
( )
. dynamic_cast, , (
), . , , , . .
, .
; ,

7 ,
;
, ,
.

109

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

4.13.

(. . 84) ,
, , .
, ,
throw , catch  (.. ) - -. , ,
:

class A { /* ... */ };
class B : public A { /* ... */ };

catch(const A& ex) { /* ... */ }


, . . throw A(...);, throw B(...);.

. , ,
- , :

, :

 (, ,
);

 ;
110

 ;
 (, -

);

, :








;
, ;
-;
;
;
. .

, (, , ).
Error, . -
, Error UserError, ExternalError Bug ,
, ,
. UserError, ,
IncorrectInput, WrongFileName, IncorrectPassword . .

catch(const IncorrectPassword& ex) { /* ... */ }


, ,

catch(const UserError& ex) { /* ... */ }


,

catch(const Error& ex) { /* ... */ }



.
, , ; catch .
111

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

; ,
, , ,
. : , .
, ,

?

; ,
,  int,  double?

,  . , , ,
112

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

5.1.
, (, , ):
void sort_int(int *array, int len) {
bool done;
do {
done = true;
for(int i=0; i<len-1; i++)
if(array[i] > array[i+1]) {
int tmp = array[i];
array[i] = array[i+1];
array[i+1] = tmp;
done = false;
}
} while(!done);
}

113


double. ,
, :
. , - sort_double, sort_int
: array
tmp, . , - . #define
, , , tmp.
++ , , . ,  ; ,
, . .
:
template <class T>
void sort(T *array, int len) {
bool done;
do {
done = true;
for(int i=0; i<len-1; i++)
if(array[i+1] < array[i] ) {
T tmp = array[i];
array[i] = array[i+1];
array[i+1] = tmp;
done = false;
}
} while(!done);
}

, template , . , class
, . ,
( T),
. , T . ,
, ,
T, (
), . , , ,
. () sort.
114


, , T. ; sort<int>
, sort int T:

int a[30];
// ...
sort<int>(a, 30);
sort<double> double. ,
, ,
(,
), <,
, .
. , . .
sort<int>,
.
,
, ; ,

sort(a, 30);
. a , sort<int>.
; ,
, .

5.2.
, , , 2.20. ,
.
SparseArrayInt Interm.
, , ,
SparseArrayInt , , , . . ,
. 64, :
115

template <class T>


class SparseArray {
struct Item {
int index;
T value;
Item *next;
};
Item *first;
public:
SparseArray() : first(0) {}
~SparseArray();
class Interm {
friend class SparseArray<T>;
SparseArray<T> *master;
int index;
Interm(SparseArray<T> *a_master, int ind)
: master(a_master), index(ind) {}
T& Provide(int idx);
void Remove(int idx);
public:
operator T();
T operator=(int x);
T operator+=(int x);
T operator++();
T operator++(int);
};
friend class Interm;
Interm operator[](int idx)
{ return Interm(this, idx); }
private:
SparseArray(const SparseArray<T>&) {}
void operator=(const SparseArray<T>&) {}
};

, SparseArray <T>, . , (. . )
, ,
;
, , , ,
 , ,
, T. .
116

-
. , :
template <class T>
SparseArray<T>::~SparseArray() {
while(first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}

Interm :
template <class T>
T SparseArray<T>::Interm::operator=(T x)
{
if(x == 0)
Remove(index);
else
Provide(index) = x;
return x;
}

, ,
( ) , SparseArray<T>, SparseArray.
: ,
,
(

).

, ,
,
,
; : (,
, ), -

.
SparseArray
.

5.3.
++ ( )  ,
, 
.
117

, ,
. 114,
( char*),
() . ,
, ,
<,
,
. , , .
, , ,
sort_less:
template <class T>
void sort(T *array, int len) {
bool done;
do {
done = true;
for(int i=0; i<len-1; i++)
if(sort_less(array[i+1],array[i])) {
T tmp = array[i];
array[i] = array[i+1];
array[i+1] = tmp;
done = false;
}
} while(!done);
}

sort_less :

template <class T>


bool sort_less(T a, T b) { return a < b; }
, ,
sort , ; sort_less
. char*,
.
, ,
template, , , , , , , ,
, . ,
1

1 ,
, ; , , .

118

(  ). :

template<>
bool sort_less<const char*>(const char *a, const char *b)
{
return strcmp(a, b) < 0;
}
: ,
sort_less sort_less<const char*>
, - .
, . , bool, , , 5.2, ,
, :
bool , ,
, , true ( false,
: - ). ,
Item ,
(
, , ).
,
, , . .
SparseArray T == bool:

template <>
class SparseArray<bool> {
// ... ...
};
++
,

.
template,

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

template <class A, class B>


119

class Cls {
/* ... */
};
, , ,
B int:

template <class X>


class Cls<X, int> {
/* ... */
};
, (class T),
T, :

template <class Z>


class Foo {
/* Foo */
};
template <class T>
class Foo<T*> {
/* Foo */
};
, Foo
,
-, 
.
, ( ) , .
, ( ) .

5.4.

,
, . ; ,


, :
120

template <class T, int len>


void sort(T *array) { /* */ }
, . , , (, 10 15) ,
: sort<int,10> sort<int,15>,
, ,
, ,

(sort<int>).
( ) . , N -
N , , ,
IntArray, 2.19.2. N -
, : ,
( , ) , ,
, ,  int 
. , ,
, . ,
( , ,
- , ),
: ,
, ,
( ).
- , IntArray .
,
 ,
,
(

,  , . .).
; (N 1)-
.
121

, ( ,
) , . ,
.
:
template <class T>
class Array {
T *p;
T init;
unsigned int size;
public:
Array(T in) : p(0), init(in), size(0) {}
~Array() { if(p) delete[] p; }
T& operator[](unsigned int idx) {
if(idx >= size) Resize(idx);
return p[idx];
}
int Size() const { return size; }
private:
void Resize(unsigned int required_index) {
unsigned int new_size = size==0 ? 8 : size;
while(new_size <= required_index)
new_size *= 2;
T *new_array = new T[new_size];
for(unsigned int i = 0; i < new_size; i++)
new_array[i] = i < size ? p[i] : init;
if(p) delete[] p;
p = new_array;
size = new_size;
}
//
void operator=(const Array<T>& ref) {}
Array(const Array<T>& ref) {}
};

, IntArray,
. -, init,
, , ( ) . -, , 16, IntArray.
, , , .
,
. MultiMatrix ,
122

, 

, .
template <class T, T init_val, int dim>
class MultiMatrix {
Array<MultiMatrix<T, init_val, dim-1>*> arr;
public:
MultiMatrix() : arr(0) {}
~MultiMatrix() {
for(int i=0; i < arr.Size(); i++)
if(arr[i]) delete arr[i];
}
MultiMatrix<T, init_val, dim-1>&
operator[](unsigned int idx) {
if(!arr[idx])
arr[idx] = new MultiMatrix<T, init_val, dim-1>;
return *arr[idx];
}
};

Array
(N 1)- ; MultiMatrix, ,
, ,
. , MultiMatrix
.
arr. , ,
Array, , ;  0,
. , (N 1) (. if ).
,  ,
MultiMatrix ,
.
,
Array (, ,
arr).
:

template <class T, T init_val>


class MultiMatrix<T, init_val, 1> {
Array<T> arr;
public:
MultiMatrix() : arr(init_val) {}

123

};

T& operator[](unsigned int idx) {


return arr.Elem(idx);
}

, ,
main:
int main() {
MultiMatrix<int, -1, 5> mm;
mm[3][4][5][2][7] = 193;
mm[2][2][2][2][2] = 251;
printf("%d %d %d %d\n",
mm[3][4][5][2][7], mm[2][2][2][2][2],
mm[0][1][2][3][4], mm[1][2][3][2][1]);
return 0;
}

193 251 -1 -1.


. , ; , double 2.5+0.7, , .
(),
.
2 ,
&var, &f f, var  , f  .
, (
, ),
( 
). , - .

2 ,
.

124

( )
, , , .
, STL.
++ STL , , ,
( ) STL, , , , ++
1999 .

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

,
STL , ++ - ( , -
). ,
++ STL
.

, C++ for real
programmers, ++ (: , 2001; 
). ,
: , ++. , STL.
: STL, .

125


. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
1.

3
5
8

1.1.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1.2. ++

. . . . . . . . . . . . . . .

2.

2.1. ,
2.1.2.

this

12

. . . . . . . . . . . . . . . . . . . . . .

2.1.1. - ()

8
10

12

. . . . . . . . . . . . . . . . . . .

12

. . . . . . . . . . . . . . . . . . . . . . . . .

13

2.1.3. .

. . . . . . . . . . . . . . .

14

2.1.4. . . . . . . . . . . . . . . . . . . . . . .

17

2.1.5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2.
2.3.

. . . . . . . . . . . . . . . . . . . . . .

2.4. .
2.5.
2.6.

. . . . . . . .

. . . . . . . . . . . .

20
21
23
24

. . . . . . . . . . . . . . . . . . . .

25

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

27

2.7. const
2.8.
2.9.

. . . . . . . . . . . . . . . . . . . . . . . . . .

29

. . . . . . . . . . . . . . . . . . . . . . . . .

32

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

34

2.10. . . . . . . . . . . . .

35

2.11.

36

. . . . . . . . . . . . . . . . . . . . . .

2.12.

. . . . . . . . . . . . . . . . .

2.13.

. . . . . . . . . . . . . . . .

2.13.1.

39
41

. . .

41

2.13.2. . . . . . . . . . . . . . . .

42

2.14.

. . . . . . . . . . . . . . . . . . . . . . .

43

2.15. .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.16.
2.17.

44

. . . . . . . . . .

46

. . . . . . . . . . . . .

48

2.18. . . . . . . . . . . . . . . . . .

49

2.19.

. . . . . . .

51

. . . . . . . . .

51

2.19.1.

2.19.2. . . . . . . . .

53

2.19.3.

55

126

++

--

. . . . . . . . . . . . .

2.19.4.

->

. . . . . . . . . . . . . . . .

2.19.5.

. . . . . . .

2.19.6. . . . . .
2.20. :
2.21.

. . . . . . . . . . . . . . . . . . . .

57
59
60
62

. . . . . . . . . . . . . . . . . . . . .

67

2.21.1. . . . . .

67

2.21.2.

69

. . . . . . . . . . . . . . . . . . . . .

3.

71

3.1. . . . . . . . . . .

71

3.2.

73

. . . . . . . . . . . . . . . . .

3.3. . . . . . . . . . . . . . . . . . . . . . . .

75

3.4.

76

. . . . . . . . . . . . . . . . . . . . . . . .

3.5.

. . . . . . . . . . . . . . . . . . . . .

3.6.

78

. . . . . . . . . . . . . . . . .

80

. . . . . . . . . . . . . . . . . . . . . . .

83

3.8. . . . . . . . .

83

3.7.

4.

85

4.1.

. . . . . . . . . . . . . . . . .

85

4.2. . . . . .

86

4.3. ;

88

. . . . . .

4.4.

. . . . . . . . . . . . . . . . . . . . . . . .

90

4.5.

. . . . . . . . . . . . . . . . . . . . . . . .

91

4.6. . . . . . . . . .

96

4.7.

99

4.8.
4.9.

. . . . . .

. . . . . . . . . . . . . . . . . . . . . . . 101

. . . . . . . . . . . . . . . . . . . . . . . . . 103

4.10. .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104

4.11. -
4.12.

. . . . . . . . 106

. . . . . . . . . . . . . . . . . . . . . 107

4.13.
5.

. . . 110
112

5.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
5.2.

. . . . . . . . . . . . . . . . . . . . . . . . . . . 115

5.3.

. . . . . . . . . . . . . . . . . . . . . . . 117

5.4.

. . . . . . 120

( ) . . . . . . . . . . . . . . . . . . . . . 125

?
?

!TM 

http://www.unicontrollers.com
, ,
GNU GPL.
Linux
Windows, , .

+----------------------------------------------+
| BEWARE OF PROGRAMMERS WHO CARRY SCREWDRIVERS |
+----------------------------------------------+

Вам также может понравиться