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

.. , ..

++
III. -
++

( -
)

, 2002
32.9773
681.142.2(075.8) -
73

.., ..
73 ++: -
. : ,
2002. 490 .

, -
,
.
- ++
32- Windows.
4 : (1) ++; (2) -
; (3) -
++ (4) Microsoft Windows Visual
C++ MFC.

- , -
Win32 - -
. -
++ Microsoft Visual C++ 5.0.

.. ..., , . -

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

2

............................................................................................................................5
1. ..................................................................6
1. - ..............6
2. .....................................................................................6
3. ......................................7
4. ...................................................8
5. ..........................................................................................8
6. .......................................................................10
7. ...............................11
8. ..........................................................................................................................14
2. - ............15
1. ...........................15
2. : . ..15
3. ...............................16
4. CRC- ............................18
5. : ......................19
6. .............................................22
7. . ................................................................................................................24
3. ++........................................................25
1. ................................................................25
2. ...........................................................................................25
3. : "" .........................................26
4. : ......................................27
5. ++ ...........................................................................28
6. .................................................................................................................32
4. ..............33
1. ..........................................................................33
2. , ................................................34
3. : ............................................................36
4. .................................................................................................................40
5. : ""...........................................41
1. .....................................................................................41
2. ........................................................................................41
3. .................................................48
4. .................................................................................................................49
6. ..........................................................51
1. ............................................................................................51
2. ........................................................................................53
3. ........................................................................................55
4. .....................................................................................56
5. .................................................................................................................58
7. ..................................................62
3
1. ........................................................................62
2. ........................................................63
3. ..........................................................63
4. ...........................................................................................67
5. ......................................................................................68
6. ...................................................................................69
7. .................................................................................................................70
8. .
......................................................72
1. .................................................................72
2. .........................................................75
3. RTTI...........................................................76
4. .....................................................78
5. .................................................................................................................81
9. STL..........................82
1. .......................................................................................................................82
2. STL ..........................................................................................82
3. .....................................................................................................................84
4. - .......................................................................................................85
5. : .....................................................................86
6. ............................................................................................88
7. .................................................................................................................90
....................................................................................................................91

4

" ++" -
-
() ++.
- -
( ), -

. -
, , -
++.
, -
++.
Microsoft Visual C++
Windows 95/98/NT. , -
, ANSI
++ Microsoft Visual C++ 5.0 Win-
dows 98.

5
1.
1. -
- -
60- . (-67, ), , -
, -
80- .
, -
.
,
- (,
CLOS), - ++ .
, , -
, .
++ , 80- . ( -
1979 .). 1994 . -
ANSI/ISO ++. 90- .
++ Java,
.
, Apple -
Macintosh,
. IBM-
Inprise Delphi.

2.
, -
. , :
1) , , -
, ;
2) , -
.
:
1) , -
( "
");
2) ;
3) , -
( ).
" " ,
,
, -
, . -
-
(. ).
-
, .

6
. , -
,
. ? -
? ,
?
: , -
, (,
). -
, ,
. .
-
. , , -
, "
". , ,
.
. .

3.
-
-, . -
, ,
.
, , , -
, (
- , " "
). ,
: ,
.
, -
, , -
. -
. ,
.
. -
: ( , ), (), ()
. , -
, , ,
.
, , , -
.
, ,
. -
.
. -
,
, (XVIII .,
).

7
4.
,
,
.
, .
, -
. -
, , ,
, .
: .
, -
. -
: - -,
. , -
, .
- -
:
1) ;
2) , .

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

5.

5.1
: ,
.
, -
. -
(), -
(,
).

8
(receiver) , -
- (client sender). , -
. -
, -
.

.
, . , -
, "-
".

5.2
:
, , .
, ,
. ..,
.

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

5.3
, , .
"" , . -
, 'C' ( class).
() (), -
, (), -
.
, - , -
, .
.
. -
, -

9
(.. ) , -
, . -
" " (. 1.1).

MaterialObject

,
CBioObject CHumanMadeObject


CAnimal CPlant Car Computer

CMammal CFish CFlower CBush CTree CMainframe CSuperomputer
Computer

CDog CHuman CPlatypus


CSeller CDoctor


CDentist CSurgeon

CComputerSeller CFoodSeller

. 1.1.

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

5.4
, , ,
(, . 1.1
, ). -
, , , -
. , -
, : ,
. , -
.
-
.

6.
( ,
):
1) .
2) ( ) -
, , -
. , -
. ,
, -
.

10
3) , -
.
4) ,
(, , ).
5) () .
, ,
.
6) ,
. , -
, ,
.

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

, ,
.

. -
-
, ,

7.
- , ,
.
, -
, -
.
, -
, -

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

.
, .
. -

11

,
, , .

7.1
( -
) .
, -
, .

, .
: , -
.
, -
.
int datastack[100];
int datatop = 0;
void init()
{
datatop = 0;
}
void push( int val )
{
if ( datatop < 100 )
datastack[datatop++] = val;
}
int top()
{
if ( datatop > 0 )
return datastack[datatop 1];
return 0;
}
int pop()
{
if ( datatop > 0 )
return datastack[--datatop];
return 0;
}

7.2

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

12
, () -
.
(. , 1972) -
:
1) -
.
2)
.
: .
: . -
.

7.3
, ,
.
(.. ) , -
. ,
,
.
, -
, . , -
:
1) .
2) ,
.
3) , ,
.
4) .

2) 3).
.

7.4 . , .
, , ,
, -
.
: . , -
, ( ..
, ). ,
. ,
push - .
, -
.
: -
,
.

13
: , -
.

, , -
, .
- , -
, , , -
" ".

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

14
2. -
- (.. , -
) , ,
. ,
(responsibility-driven design).
-
, , , ,
. , -
.

- - , -
.
. ,
, -
.
.

1.
, -
. -
" ". "-
" "".
"" :
, , , -
. -
.

.
, "" :
.
( -
) , -
, . -
, .

.
- -
"" . -
.

2. : .
" " -
. . -
, .
, -

15
,
.

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

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

16
,
, ().
3)

. : -
. -
. -
.
, .
,
. ,
. -
-
.
4)
,
. ,
. ,
-
, .
5)
, -
, -
. .
. ,
, ,
, .
, , -
.
6)
, -
. , -
( ), -
. . -
. -
.
, , -
, .
.
7)
.
-
. ,
, -
, (..,
).

17
4. CRC-
-
, -
. .. , .
, ,
. ,
:
-
;

, .
-
. "/". -
: ? : -
? , , -
. - -
.
-
. -
, , -
(. 2.1). CRC- Com-
ponent, Responsibility, Collaborator (, , ).

()

,

. 2.1. CRC-

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

18
5. :

5.1
. , -
.
, MainWin.
( , , ) -
:
1) .
2) .
3) .
4) , .
5) .
6) .
7) .
.
, , -
. : -
.
, ,
, . .. -
. ,
, -
.
. ,
, CRC-
MainWin (. 2.2).

MainWin ( )


-

:


. 2.2. CRC- MainWin.

, , -
. , ? -
: , , .
?
? -
.
19
, -
. , -
.
:
,
.
-
( -
, , ).
. , -
.

5.2
-
Deal. , . -
, ,
(Date). ,
.
: , ,
, .
Deal .
:
, . ,
, .
Date.
Date Deal , -
.
, -
. ( ,
) , ( ,
..), , (, -
), . -
Person,
.
-
, .
, . -
Deal. -
,
. -
Plan Manager.
.
, Plan Manager
, .
Date.
, . Date

20
, (- , -
.).
,
(. 2.3). . 2.3 ,
. , Date -
Deal Deal Database.

MainWin

Plan Person
Manager Database

Date Person

Deal
Database

Deal

. 2.3.
"".

5.3
, . 2.3,
. -
. -
(. 2.4). . 2.4 - -
. . -
-
. (, , )
.

MainWin Plan Date Person


Manager Database
browse()
display()
display()
browse()
t () newPerson()
. 2.4. .

21
6.

6.1
. ,
( ), -
, -
. .
, Deal , -
, ,
. Deal ,
, , . -
. ,
.
. ,
MainWin . -
, .

6.2
. -
. Deal
. : , ,
, .
, Deal. ,
, .
""
. .
, , -
. .. -
. , -
. Deal. -
(, , ), -
.

6.3

. , , -
, .
, -
. Date , -
. Date
browse(), Deal Database.
.
, Deal Database .
, ,
. , .. -

22
,
.
, :

, .
-
.
-
, -
.

6.4
, , -
, . ,
( ), . -
, ,
. .
, CRC- ,
. .
, . -
, .
, ( , -
) .

6.5
, , .
, , .
, -
:
, ;
, -
(., CardReader Card_Reader
cardreader).
(., , TermProcess
, (terminal process) ,
(terminate process)).
(., empty()
, ,
?).
( 0 O, 1 l, 2 Z, 5 S).
, , -
true false (., PrinterIsReady ,
true , PrinterStatus
).
, , CRC- -

23
(. 2.5). ,
.
CRC- -
, ,
.

Date ( -
)
, -

Date( year, month, day )

Date
Display()


Edit()


ViewPersons()

,

. 2.5. CRC- Date

7. .
1)
: , ,
, .
2)
( ) " ".
3) CRC- " -
",
.

24
3. ++
++,
, . -
,
. . -
,
.
. -
. .

1.
(encapsulation) ,
, , ,
.
.
.
, , , -
, . ,
, ,
. , , , -
. -
, .
"". -
: push, pop, top .. , , -
, , -
, , 100
int n[100]. .. .
() .
"".
"
" "". -
. , -
.
. -
, .
.
, , -
.

2.
, , 4 -
(, , , ):
( , Data Managers);
(Data Sources Data Sinks);
(Views);

25
,
(Facilitators).
, -
. , , .
-
-. , -
CCard (-
) . -
.
.
-
. .
(,
). ,
, ( )
( ) .
,
.
,
.
, -
( , , -
) ( -
).
,
. -
. ,
, , .
, -
, -
. ,
, .
, , ().

3. : ""
,
"" CCard,
.
. 3.1 CRC-, -
. ,
CCard, -
. CCard , -
, , , .
,
.

26
CCard



" "
" "

. 3.1. CRC- CCard.

CRC- , -
. -
-
. ,
( ).
. 3.2 CRC- CCard -
. ,
(, " "),
. -
.
CRC-
. RC- -
.

CCard
( )
Suit
Rank
Color
Draw, Erase

IsFaceUp, Flip -
" "

. 3.2. CRC- CCard.

4. :
.
(" ") ,
. :
,
.
, -
.

27
: (interface) -
(implementation). . -
, .
, .
, , -
.

5. ++

5.1
-
"*.h", "*.cpp".
,
.
class (. -
3.1). ,
. private:
, (-
). public: -
, . ,
, -
. ,
, , -
, - ,
.
++ -
, - .
//
enum Suit { Heart /* */, Club /* */,
Diamond /* */, Spade /* */ };
//
enum Color { Red, Black };
class CCard {
public:
//
CCard( Suit, int );
//
Color GetColor();
bool IsFaceUp();
int GetRank();
Suit GetSuit();
//
void Draw( CWindow& wnd, int x0, int y0 );
void Erase( CWindow& wnd );
void Flip();
private:
bool isFaceUp; // " "/" "
int rank; //
Suit suit; //
};
3.1. CCard ( card.h).

28
, -
. , -
, , -
.
CCard(Suit, int) .
, .
.
( ).
Draw()
CWindow, , .
, , .. .
- . -
suit, -
GetSuit. , rank GetRank -
.
CCard , -
. CCard
3.2.

#include "card.h"

CCard::CCard( Suit sv, int rv )


{
suit = sv;
rank = rv;
isFaceUp = true;
}

int CCard::GetRank()
{
return rank;
}

Color CCard::GetColor()
{
return (Color)( suit % 2 ); //
}
3.2. CCard (card.cpp).

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

5.2
, , ,
++ . -
.
, ( ) -

29
,
. -
, , return,
, . -
.
- inline:
inline int CCard::GetRank()
{
return rank;
}

-
, 3.3. -
, -
.
, -
, .
class CCard {
public:
//
CCard( Suit, int );
CCard();
CCard( const CCard& );

//
Color GetColor();
bool IsFaceUp() { return isFaceUp; }
int GetRank() { return rank; }
Suit GetSuit() { return suit; }
//
void Draw( CWindow& wnd, int x0, int y0 );
void Erase( CWindow& wnd );
void Flip() { isFaceUp = !isFaceUp; }

private:
bool isFaceUp; // " "/" "
int rank; //
Suit suit; //
};
3.3. CCard .

5.3
(polymorphism) ,
, ( -
) . ++
. .
.
-
.

30
, CCard
, :
, CPoint:
class CCard {
public:
...
void Draw( CWindow& wnd, int x0, int y0 );
void Draw( CWindow& wnd, CPoint& topLeft );
...
};

, , .
print
open. f , -
f . -
f. -
, ,
, .

5.4
, ,
++. -
. , +
, ,
. ++ -
, . ,
, , =, (), -
[] ->.
, , , -

, -
.
, -
:
class CComplex {
public:
CComplex( double r, double i ) { re = r; im = i; }
CComplex operator+(CComplex);
CComplex operator*(CComplex);
private:
double re, im;
};

+ * -
operator+ operator*. , , b c
CComplex, b+c ( ) -
b.operator+(c). .. -
.
31
:
CComplex CComplex::operator+(CComplex c1)
{
return CComplex( re + c1.re, im + c1.im );
}

6.
1)
, . -
: , . -
. -
, ,
.
2) ,
. - , , -
. , -
.
3) CCard (. 3.2)
.
. ,
, .
4) . -
addi() . -
?
class example1 { class example2 {
public : public :
int i; int i;
};
int addi( int j )
int addi( example1& x, int j) { i += j; return i; }
{ }
x.i += j;
return x.i;
}

32
4.
1.
" "
. 1- -
:
, -
.
, ,
. -
, ,
( ).
:
(, ), ,
.
++ -.
. -
( ):
< ->.< >(< >);
, theCard CCard,
win (50, 45), -
:
theCard.Draw( win, 50, 45 );
++, - -
, . -
- . ,
:
if ( theCard.IsFaceUp() )
{
...
}
else
{
...
}
- -
this, - (.. ,
-). , - CCard.GetColor() -
:
Color CCard::GetColor()
{
if ( this->GetSuit() == Heart || this->GetSuit() == Diamond )
return Red;
return Black;
}

++ this
, .. - -

33
.
- GetColor() :
Color CCard::GetColor()
{
if ( GetSuit() == Heart || GetSuit() == Diamond )
return Red;
return Black;
}

, this , -
,
:
void COneClass::aMessage( CAnotherClass& ca, int x )
{
//
// - ca CAnotherClass
ca.doSomething( this, x );
}

2. ,
++ , , -
.
, (.. -
).
++ -
. . -,
. .
, .
-,
new .
" " (
):
class CComplex {
public:
CComplex()
{ re = im = 0.0; }
CComplex( double re_val )
{ re = re_val; im = 0; }
CComplex( double re_val, double im_val )
{ re = re_val; im = im_val; }
...
private:
double re, im;
};
-, ++
. , -
. -
, -
. ( ) .

34
-
CComplex :
CComplex pi = 3.14159; //
CComplex e( 2.71 ); //
CComplex i(0, 1); //
CComplex c; //
new,
, :
CComplex* pc = new CComplex( 3.14159, -1.0 );
, -
. "
" ( ):
CComplex c_arr1[25];
CComplex* c_arr2 = new CComplex[25];
, ,
delete ( delete[] -
). -,
. -
, "" (~). -
, .

( -
, ). CTrace -
,
. -
. ,
. : -
, CTrace, , -
.
.
.
class CTrace {
public:
CTrace( char* );
~CTrace();
private:
char* msg;
};
CTrace::CTrace( char* s )
{
msg = new char[ strlen(s) + 1 ];
strcpy( msg, s );
cout << " " << msg << "\n";
}
CTrace::~CTrace()
{
cout <<" " << msg << "\n";
delete msg;
}

35
,
, CTrace . -
, .. -
. -
:
void functionA()
{
CTrace t( "functionA" );
functionB( 10 );
}
void functionB( int x )
{
CTrace t( "functionB" );
if ( x < 5 )
{
CTrace t( "functionB: x < 5" );
...
}
else
{
CTrace t( "functionB: x >= 5" );
...
}
...
}

functionA(), -
CTrace
functionA() functionB() :
functionA
functionB
functionB: x >= 5
functionB: x >= 5
functionB
functionA

3. :
, ,
. :
, -
.
. 92 ,
12, -
. . 4.1.

. 4.1. .

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

3.1
, -
.
, , .
-
.
-
: . .., -
: , , ,
, .
N
1 N, . -
.
,
.

CQueen: CQueen:
Initialize , - row (
- )
column ()
Advance neighbor ()

CanAttack ,
-

. 4.2. CRC- CQueen.

, CRC- CQueen
() , . 4.2.
, .

37
3.2 CQueen
CQueen.
pNeighbor - (
pNeighbor=0). Initialize .

class CQueen {
public:
CQueen( int, CQueen* );
CQueen* GetNeighbor() { return pNeighbor; }
bool FindSolution();
bool Advance();
void Print();
private:
const int column; // ( 1 8)
int row; // ( 1 8)
CQueen* pNeighbor; // -
bool CanAttack( int r, int c );
};

- column ( ) .
. ..
, column -
.
-
.
CQueen::CQueen( int col, CQueen* pNgb ) :
column( col ),
pNeighbor( pNgb ),
row( 1 )
{
}

3.3 - CQueen
, -, -
, . , ( -
" ", ).
, , .
"", . -
. -
FindSolution():
bool CQueen::FindSolution()
{
if ( pNeighbor )
if ( pNeighbor->CanAttack( row, column ) )
return Advance();
return true;
}

38
-
CanAttack(), ,
. ,
.
bool CQueen::CanAttack( int r, int c )
{
//
if ( row == r )
return true;
//
int deltaCol = c - column;
if ( ( row + deltaCol == r ) || ( row - deltaCol == r ) )
return true;
// , (r, c)
if ( pNeighbor )
return pNeighbor->CanAttack( r, c );

return false;
}

-
Advance(). . -
, . -
,
, 1- .
bool CQueen::Advance()
{
//
if ( row < 8 )
{
row++;
return FindSolution();
}
// ,
//
if ( pNeighbor )
if ( pNeighbor->Advance() )
{
// 1-
row = 1;
return FindSolution();
}
return false;
}

, , .
Print():
void CQueen::Print()
{
if ( pNeighbor )
pNeighbor->Print();
cout << ": " << row << "; C: " << column << "\n";
}

39
3.4
.. ,
-, , -
. main() pLastQueen -
( ). ,
CQueen , .

main().
void main()
{
CQueen* pLastQueen = NULL;
for ( int i = 1; i <= 8; i++ )
{
// i-
pLastQueen = new CQueen( i, pLastQueen );
if ( !pLastQueen->FindSolution() )
cout << " .\n";
}
//
pLastQueen->Print();
// -
while ( pLastQueen )
{
CQueen* pPrevQueen = pLastQueen->GetNeighbor();
delete pLastQueen;
pLastQueen = pPrevQueen;
}
}

4.
1) MS Visual C++ -
queen.h ( CQueen), queen.cpp (
CQueen) testprg.cpp ( ). -
, . ,
.
2) ,
. ,
?
3) , N ? ..
N NxN?
N, (, N=2
N=3). ?
4) ,
. -
OpenGL. -
?
: , -
. -
Sleep(int dt) Win32 API ( dt -
).

40
5. : ""
,
. ,
1-4
OpenGL. OpenGL Windows :
. -
,
Windows API.
""
,
.

1.
, -
. 4- . 15
1 (. 5.1).
-
, -
. -
. -
. , -
(. 5.1).

. 5.1. 4- .

2.
, .

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

41
,
. -
,
.

2.1 CRect ()
CRect ,
-
. -
. ,
- .
class CRect {
public :
//
CRect()
{ x1 = y1 = x2 = y2 = 0; }
CRect( int nx1, int ny1, int nx2, int ny2 )
{ x1 = nx1; y1 = ny1; x2 = nx2; y2 = ny2; }
//
void SetRect( int left, int top, int right, int bottom )
{ x1 = left; y1 = top; x2 = right; y2 = bottom; }
//
void OffsetRect( int dx, int dy )
{ x1 += dx; y1 += dy; x2 += dx; y2 += dy; }
//
void CenterPoint( int* x, int* y )
{ *x = (x1 + x2)/2; *y = (y1 + y2)/2; }
//
bool IsRectEmpty()
{ return ( x1 == x2 && y1 == y2 ); }
//
int Width() { return x2 - x1 + 1; }
//
int Height() { return y2 - y1 + 1; }
// another
CRect IntersectRect( CRect& another );
//
void NormalizeRect();
//
int x1, y1, x2, y2;
};

() , ..
, -
.
,
(x1, y1) (x2, y2) .
. -
- IntersectRect()
.

42
2.2 CWall ( )
Wall :
class CWall {
public:
CWall( int left, int top, int right, int bottom,
double cf, CWall* pNextWall );
//
void Draw();
// ,
void HitBy( CBall* pBall );
CRect GetRegion() { return region; }
CWall* GetLink() { return pLink; }
private:
CWall* pLink;
CRect region; //
double convertFactor; // ,
// ,
//
};

pLink CWall. -
,
:
CWall::CWall( int left, int top, int right, int bottom,
double cf, CWall* pNextWall )
{
convertFactor = cf;
region.SetRect( left, top, right, bottom );
pLink = pNextWall;
}

.
OpenGL:
void CWall::Draw()
{
glColor3ub( 0, 255, 0 );
glRecti( region.x1, region.y1, region.x2, region.y2 );
}

, -
convertFactor.
convertFactor=0, convertFactor=Pi. -
:
void CWall::HitBy( CBall* pBall )
{
pBall->SetDirection( convertFactor - pBall->GetDirection() );
}

43
2.3 CHole ( )
CHole:
class CHole {
public:
CHole( int x, int y, CHole* pNextHole );
//
void Draw();
// ,
void HitBy( CBall* pBall );
CRect GetRegion() { return region; }
CHole* GetLink() { return pLink; }
private:
CHole* pLink; //
//
CRect region; //
};

- :
CHole::CHole( int x, int y, CHole* pNextHole )
{
// (x, y)
region.SetRect( x - 5, y - 5, x + 5, y + 5 );
pLink = pNextHole;
}

void CHole::Draw()
{
// , region
glColor3ub( 255, 255, 0 );
glPointSize( (float)region.Width() );
glEnable( GL_POINT_SMOOTH );
glBegin( GL_POINTS );
int cx, cy;
region.CenterPoint( &cx, &cy );
glVertex2i( cx, cy );
glEnd();
glDisable( GL_POINT_SMOOTH );
}

. ,
.
,
.
void CHole::HitBy( CBall* pBall )
{
//
pBall->SetEnergy( 0.0 );
if ( pBall->IsCue() )
pBall->SetCenter( 50, 108 );
else
{

44
pBall->SetCenter( 10 + saveRack*15, 250 );
saveRack++; //
}
}

2.4 CBall ( )
,
:
class CBall {
public:
CBall( int x, int y, bool fc, CBall* pNextBall );
//
void Draw();
// ,
//
void Update();
// ,
void HitBy( CBall* pBall );
// OX ,
// (dx, dy)
double HitAngle( double dx, double dy );
// -
void SetEnergy( double v ) { energy = v; }
void SetCenter( int newx, int newy );
void SetDirection( double newDir ) { direction = newDir; };
CRect GetRegion() { return region; }
CBall* GetLink() { return pLink; }
double GetEnergy() { return energy; }
void GetCenter( int* x, int* y );
double GetDirection() { return direction; }
bool IsCue() { return fCue; }
private:
CBall* pLink; //
CRect region; // ,
double direction; // (
// OX)
double energy; //
bool fCue; //
};

direction (
), energy ( ) fCue, true
.
( ),
. .
CBall::CBall( int x, int y, bool fc, CBall* pNextBall )
{
SetCenter( x, y );
SetDirection( 0 );
SetEnergy( 0.0 );
pLink = pNextBall;
fCue = fc;
}

45
.
- Draw().
void CBall::Draw()
{
if ( IsCue() )
glColor3ub( 255, 255, 255 ); //
else
glColor3ub( 0, 0, 255 ); //
glPointSize( (float)region.Width() );
glEnable( GL_POINT_SMOOTH );
glBegin( GL_POINTS );
int cx, cy;
region.CenterPoint( &cx, &cy );
glVertex2i( cx, cy );
glEnd();
glDisable( GL_POINT_SMOOTH );
}

- Update()
,
. , -
, . ,
- fBallMoved true.
, . -
: , .
void CBall::Update()
{
//
if ( energy <= 0.5 )
return;
fBallMoved = true;
//
energy -= 0.05;
//
// . 2.0
// -
int dx = (int)( 2.0*sqrt(energy)*cos(direction) );
int dy = (int)( 2.0*sqrt(energy)*sin(direction) );
region.OffsetRect( dx, dy );
//
CHole* hptr = listOfHoles;
while ( hptr )
{
CRect is = region.IntersectRect( hptr->GetRegion() );
if ( !is.IsRectEmpty() )
{
hptr->HitBy( this );
hptr = NULL;
}
else

46
hptr = hptr->GetLink();
}
//
CWall* wptr = listOfWalls;
while ( wptr )
{
CRect is = region.IntersectRect( wptr->GetRegion() );
if ( !is.IsRectEmpty() )
{
wptr->HitBy( this );
wptr = NULL;
}
else
wptr = wptr->GetLink();
}
//
CBall* bptr = listOfBalls;
while ( bptr )
{
if ( bptr != this )
{
CRect is = region.IntersectRect( bptr->GetRegion() );
if ( !is.IsRectEmpty() )
{
bptr->HitBy( this);
break;
}
}
bptr = bptr->GetLink();
}
}

, , , -
.
.
void CBall::HitBy( CBall* pBall )
{
//
pBall->SetEnergy( pBall->GetEnergy()/2.0 );
//
energy += pBall->GetEnergy();
//
int cx1, cy1, cx2, cy2;
GetCenter( &cx1, &cy1 );
pBall->GetCenter( &cx2, &cy2 );
SetDirection( HitAngle( cx1 - cx2, cy1 - cy2 ) );
//
double da = pBall->GetDirection() - GetDirection();
pBall->SetDirection( pBall->GetDirection() + da );
}

// OX (dx, dy).
// (0,PI) (-PI,0)
double CBall::HitAngle( double dx, double dy )

47
{
double na;
if ( fabs(dx) < 0.05 )
na = PI/2;
else
na = atan( fabs(dy/dx) );
if ( dx < 0 )
na = PI - na;
if ( dy < 0 )
na = -na;
return na;
}

3.
-
OpenGL: -
, .
MouseButtonDown()
.
" ".
void CALLBACK MouseButtonDown( AUX_EVENTREC* event )
{
// ,
// (.. event
// ,
// )
int mouse_x = event->data[0];
int mouse_y = WINDOW_HEIGHT - event->data[1];
//
pCueBall->SetEnergy( 20.0 );
// " "
int cx, cy;
pCueBall->GetCenter( &cx, &cy );
pCueBall->SetDirection( pCueBall->HitAngle( mouse_x-cx, mouse_y-cy ) );
//
fBallMoved = true;
}

Idle() (
- fBallMoved) -
. ,
, -
.
//
void CALLBACK Idle()
{
// ,
//
if ( !fBallMoved )

48
return;
//
fBallMoved = false;
CBall* bptr = listOfBalls;
while ( bptr )
{
bptr->Update();
bptr = bptr->GetLink();
}
Display(); //
Sleep( 25 ); // 25
}

:
.
void CALLBACK Display()
{
glClear( GL_COLOR_BUFFER_BIT );
//
CWall* pWall = listOfWalls;
while ( pWall )
{
pWall->Draw();
pWall = pWall->GetLink();
}
//
CHole* pHole = listOfHoles;
while ( pHole )
{
pHole->Draw();
pHole = pHole->GetLink();
}
//
CBall* pBall = listOfBalls;
while ( pBall )
{
pBall->Draw();
pBall = pBall->GetLink();
}
auxSwapBuffers();
}

4.
1) OpenGL -
"" (prg5_1.cpp).
. , -

. ,
, . -
, .

49
Visual C++ ClassView (-
) . , (. 5.2) -
, - -, -
.

. 5.2. ClassView ( ) MS
Visual C++. ,
"". CWall .

2) , ?
15- 5 , 5 5 .
3) ,
.

50
6.
, -
. -
. 1- , -
, .
, -
. , -
, .
, , , .
, -
, . -
: -
"", "".

1.
-
(, -
) ( , -, -
, ..). -
. , -
, (
) -
. -
, -
:
class CTime ... //
//
struct ElectricalData {
CTime timeStamp;
int id;
double fuelCell1Voltage, fuelCell2Voltage;
double fuelCell1Amperes, fuelCell2Amperes;
double currentPower;
};

:
1) ElectricalData , -
, timeStamp currentPower (,
,
).
2) .. , (-
)
. , , -
- . ,
, , -
.

51
3) .
( ,
..), -
.
,
,
.
, -
- , - -
.

.
. .
,
; , -
:
// " "
class CTelemetryData {
public:
CTelemetryData();
virtual ~CTelemetryData();
virtual void Transmit();
CTime CurrentTime();
protected:
int id;
CTime timeStamp;
};

virtual -
, .
CTelemetryData , (
) Transmit() CurrentTime(),
. id timeStamp
. CurrentTime() , -
timeStamp , .
, ++
:
(public) ;
(protected) ;
(private) .

, CElectricalData:
class CElectricalData : public CTelemetryData {
public:
CElectricalData( double v1, double v2, double a1, double a2);
virtual ~CElectricalData();
virtual void Transmit();
double CurrentPower();
protected:

52
double fuelCell1Voltage, fuelCell2Voltage;
double fuelCell1Amperes, fuelCell2Amperes;
};

CTelemetryData,
, (
Transmit()
urrentPower()).

2.
, -
( )
( ) . , -
, .
, CTelemetryData
CElectricalData. -
. "" "".
CElectricalData -
CTelemetryData. -
.

CTelemetryData . 6.1. -
. , CCameraData CSensorData,
CTelemetryData.

CTelemetryData

CElectricalData CPropulsionData CSensorData

CSpectrometerData CCameraData CRadiationData

. 6.1. .

, . 6.1 -
, . -
CElectricalData CSpectrometerData. -
, (CSensorData
CTelemetryData), . , , -
. , -
, .
(. 6.1).
.
, -

53
. , ++,
,
.
-
. -
, . -
, . ,
CBall, CGraphicalObject, -
( -
):
CBall::CBall( int x, int y, int c ) :
CGraphicalObject( x, y )
{
//
...
}

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

-
. -
"". , , - ,
.
, -
. CElectricalData -
(id timeStamp) -
( fuelCell1Voltage, fuelCell2Voltage,
fuelCell1Amperes, fuelCell2Amperes).
. -
CElectricalData urrentTime() (-
), urrentPower() ( )
Transmit() ( ).
++
,
. , ( Transmit()
), , (CurrentTime())
.

54
3.
(, -
) Transmit() CTelemetryData :
void CTelemetryData::Transmit()
{
// id
// timeStamp
}

ElectricalData
, :
void CElectricalData::Transmit()
{
CTelemetryData::Transmit();
//
//
}


CTelemetryData::Transmit().
(id timeStamp), -
.
:
CTelemetryData telemetry;
CElectricalData electrical(5.0, -5.0, 3.0, 7.0);
, :
void transmitFreshData( CTelemetryData& d, const Time& t)
{
if ( d.CurrentTime() >= t )
d.Transmit();
)

, ?
transmitFreshData( telemetry, Time(60) );
transmitFreshData( electrical, Time(120) );
.
, ,
. ?
transmitFreshData() ,
d.Transmit()! . d
. ,
, ,
.
(., ) ,
, , ,
. ,
. -
-

55
. -
, , "+", .
. , ++
,
. .., ++ -
:
1) ;
2) .
-
switch. , -
, , -
kind, .
.
:
enum TelemetryType { Electrical, Propulsion, Spectrometer };
void transmitFreshData( TelemetryData* pData, Time t )
{
if ( pData->currentTime >= t )
switch ( pData->kind )
{
case Electrical :
transmitElectricalData( (ElectricalData*)pData );
break;
case Propulsion :
transmitPropulsionData( (PropulsionData*)pData );
break;
}
}

,
TelemetryType, -
( kind )
switch. .
.
,
. , -
" ".

4.

4.1 -
Transmit():
void CElectricalData::Transmit()
{
CTelemetryData::Transmit();
//
//
}

56
++, - ,
-
. , , - -
(.. -
). ++ -
, ,
- (, CTelemetryData::Transmit()).
-
. -
.

4.2
. 6.1 .
, CElectricalData CTelemetryData.
:
CTelemetryData telemetry;
CElectricalData electrical( 5.0, -5.0, 3.0, 7.0 );
:
telemetry = electrical; //electrical - telemetry
, : -
. -
, , electrical,
,
telemetry CTelemetryData.
, ..
TelemetryData CElectricalData:
electrical = telemetry;
, y x -
, x y
.

4.3
.4.2,
, .
. , -
, ,
, .
( ) "" .
++ , -
. -
. -
, ,
.
,
. ,
57
CBall , , -
Link (" ") :
class Link {
protected:
Link* pLink;
public:
CLink* GetNext();
void SetLink(CLink* pElem);
};
void CLink::SetLink(CLink* pElem)
{
pLink = pElem;
}
CLink* CLink::GetNext()
{
return pLink;
}
CBall CLink. -
SetLink() , .
GetNext(). , -
CLink, CBall. ,
Ball, , -
. Ball , -
GetNext(). -
, :
class Ball : public Link {
...
public:
...
Ball* GetNext();
...
};
Ball* Ball::GetNext()
{
return dynamic_cast<CBall*>(CLink::GetNext());
}
, - GetNext() , .. -
. ,
++ ,
. dynamic_cast()
++ RTTI (Run-Time Typing Information
). RTTI -
(CBall*), -
.

5.

5.1
:
class CBase {
public :

58
virtual void Iam() { cout << "CBase\n"; }
};
CBase -
Iam() (" "), . -
Iam().
CBase* -
Iam() .

5.2
. 6.2 ,
. CShape "", "-
" "". " " (CBox)
" " (CWireBox).
,
,
. GLAUX.
CShape .
-:
Draw ;
Move ;
GetCenter .
- GetCenter Move
. ,
, , Draw() -
.

CShape

CSphere CPyramid CBox

CWireBox

. 6.2. " ".

CSphere radius -
(SetRadius) . - Draw

enter. Box height (), width () depth
() .
Draw
center. CWireBox
CBox, Draw .

59
:
CShape* shapes[10];
//
...
for ( int i = 0; i < 10; i++ )
shapes[i]->Draw();
, -
CShape.
, -
.

5.3
,
5- . "", "" "" "-
". :
class CGraphicalObject {
public:
CGraphicalObject( int left, int top, int right, int bottom );
// ,
virtual void Draw() {;}
virtual void Update() {;}
virtual void HitBy( CGraphicalObject* pObj ) {;}

// -
CRect GetRegion() { return region; }
CGraphicalObject* GetLink() { return pLink; }
protected :
CRect region;
CGraphicalObject* pLink;
};
, -
. - Draw(), Update() HitBy()
, .
CGraphicalObject::CGraphicalObject( int left, int top,
int right, int bottom )
{
region.SetRect( left, top, right, bottom );
}

Ball, Wall Hole


GraphicalObject, ,
:
class CHole : public CGraphicalObject {
public:
CHole( int x, int y, CGraphicalObject* pNextObj );
//
virtual void Draw();
// ,
virtual void HitBy( GraphicalObject* pObj );
};

60
- HitBy Ball*. -
dynamic_cast. ( -
MS Visual C++, RTTI -
ProjectSettingsC/C++C++ LanguageEnable Run-Time Type Informa-
tion (RTTI))
void CHole::HitBy( CGraphicalObject* pObj )
{
CBall* pBall = dynamic_cast<CBall*>( pObj );

if ( pBall )
{
pBall->SetEnergy( 0.0 );
if ( pBall->IsCue() )
pBall->SetCenter( 50, 108 );
else
{
pBall->SetCenter( 10 + saveRack*15, 250 );
saveRack++; //
}
}
}

, -
. , ,
:
void CALLBACK Display()
{
glClear( GL_COLOR_BUFFER_BIT );
CGraphicalObject* pObj = listOfObjects;
while ( pObj )
{
pObj->Draw();
pObj = pObj->GetLink();
}
auxSwapBuffers();
}

-
Draw() . , -
CBall, CWall CHole.
Ball::Update(), ,
-, .

61
7.
1.
: , -
, , , .
:
.
() .
.
.
, .
, , ,
.
, .
. -,
- . , , -
: , , .
-, - . ,
, . -
, .
: -
, , , .
. -, -
"/" ( ), "is-a".
, : , -
"". , "/", -
"part of". , . -, -
(). ,
, , . : ,
.
-
. , - -
:
;
;
;
;
.
-
.
, , -
.
. -
, -
. (),
.

62
.
++ ( ) -
, .

2.
-
.
, -
, . , -
X Y, "X
Y". (..
), , X Y -
.
(" ") , -
,
. , Car -
Engine, , , Car -
Engine Engine Car. Car -
Vehicle,
MeansOfTransportation.
, ,
"X Y " .
.
. , . 3,
, -
.

3.
,
"" ( CSet) " -
" (CList). CList . -
, List :
class List {
public:
List();
void AddToFront(int);
int FirstElement();
int Length();
bool IsIncludes(int);
int Remove(int);
...
};

"" ,
, , , -
, .

63
, "",
, , -
, .

3.1.
, "" .
, .
,
-. , Set -
- data CList.
class CSet {
public:
CSet();
void Add(int);
int Size();
bool IsIncludes(int)
private:
CList data;
};

CList - "-
", CSet. -
, (
), .
- CSet -
CList. , - IsIncludes Size
- :
int CSet::Size()
{
return data.Length();
}
int CSet::IsIncludes( int newValue )
{
return data.IsIncludes( newValue );
}

- Add() -
, .. , -
( .. ):
void CSet::Add( int newValue )
{
if ( !IsIncludes( newValue ) )
data.AddToFront( newValue );
}
, -
. ,
, CSet List. -
. 7.1.
64
CSet CList

. 7.1. .

, -
List Set , -
.

3.2.
-
. , -
, . -
.
, .

CList

CSet

. 7.2. .

5- . -
. 7.2. , -
CSet List. -
List, -
.
class CSet : public CList {
public:
CSet();
void Add(int);
int Size();
};
, -
. CList -
.
- -
, - IsIncludes CList
- . - -
-
CList:
void CSet::Add( int newValue )
{
if ( !IsIncludes( newValue ) )
AddToFront( newValue );
}

65
Add . 3.1.

. , -
, . , -
, .

3.3.
. 3.1-3.2 ,
"". -
.
. , -
, - .
CSet , -
, -
. , -
- CList.
- , , -
- . ,
, - ,
. , CSet ,
(-
- IsIncludes). -
CList. .., :
,
.
,
: , -
. , -
- . -
. , -
IsIncludes,
Remove.
-
- ,
. , -
CSet
CList AddToFront.
, List
, . ..,
CSet (, ) -
CSet. -
, CSet
CList, .

66
?
"X Y".
" "? .. -
, CList, CSet?
"" "", , .
.

4.
, -
. . 7.3 , -
. CProduct , -
, CSale , -
. : ,
, , , , .
-productSold -lastSale
CProduct CSale
* 1

. 7.3. .

++ " -
", , :
class CProduct;
class CSale;
class CProduct {
public:
...
protected:
CSale* lastSale;
};
class CSale {
public:
...
protected:
CProduct** productSold;
};

"--":
, CSale -
.
, () .
, ( , ,
, ) ,
( -
, , ). -
. , , -
.
" ".
(.., , ).
:
"--"
67
"--"
"--".
"--" . ,
CSale
CCreditCardTransaction:
.
"--" . ,
Customer () -
SalePerson ( ), -
.

5.
-
. , -
. -
; ,
.
,
CTemperatureRamp,
:
class TemperatureRamp {
public:
TemperatureRamp();
virtual ~TemperatureRamp();
virtual void Clear();
virtual void Bind( int temperature, int minute );
int TemperatureAt( int minute );
protected:
...
};

, ,
. , -
: TemperatureRamp, -
Heater CTemperatureController.
CTemperatureController :

class CTemperatureController {
public:
CTemperatureController( int location );
~CTemperatureController();
void Process( const CTemperatureRamp& );
int Schedule( const CTemperatureRamp& );
private:
CHeater h;
};

CTemperatureController CHeater .
CTemperatureRamp -

68
CTemperatureController. ,
CTemperatureController CTemperatureRamp.

. , , ,
() ().
, -.
-. ,
CTemperatureController Schedule , -
, CPredictor ( ). -
,
CTemperatureController, . -
, - -
.

6.
" " Stack.
class CStack {
public:
CStack();
void Push( int val );
int Pop();
bool IsFull();
protected:
int data[100];
int top;
};

: -
.
,
.
template<class T>
class CStack {
public:
CStack();
void Push( T val );
T Pop();
bool IsFull();
protected:
T data[100];
int top;
};

,
T .
-
, :
CStack<double> doubleStack;
CStack<GraphicalObject*> graphStack;

69
doubleStack ( ) graphStack ( -
) ,
. ,
CStack.
- -
, :
template <class T>
CStack<T>::CStack()
{
top = 0;
}

template <class T>


void CStack<T>::Push( T val )
{
data[top++] = val;
}

. , -
doubleStack graphStack ++ -
- , , -
GraphicalObject.
Stack -
GraphicalObject . 7.4.

CGraphicalObject

CStack

-< >
+< - >()

. 7.4. .

. 7.4,
CStack, , , GraphicalObject.
-
.
-
. , -
. ,
, . ++
, -
.

7.
1) , -
. ,

( -
).

70
"", " ", "" " -
" .
"", "" "" -
(, 4 ).
"", "- " "
" .
"" " " -
( "" - "-
").
2) , " " CList
" " COrderedList, -
, ( -
, , ,
" " " "). -
? (
++ ).
3) .
"" CImage,
.
: -
/ . -
1 .
.
- :
(/ -
), / -
. ,
.
, CImage - -
. . -
CImage , ,
,
.
4) "" - ,
( ) . -
CList CStack , , -

. .
?

71
8. .

1.
++ , -
(exception handling).
, .
()
: try, catch throw.
, -
, try.
try , throw -
. ,
catch. try, -
. try catch
:
try (
//
}
catch (typel arg) {
// type1
}
catch (type2 arg) {
// type2
}
...
catch (typeN arg) {
// typeN
}
try , -
. ,
main() (
).
catch, -
. try
catch.
try (.. , -
try ,
catch, try). -
catch arg.
, catch type,
arg .
throw:
throw ;
throw try,
, ( ).
throw .
, .
72
, -
catch, -
.
8.1.
try, , catch
.
#include <iostream.h>

void main()
{
cout << "\n";
try {
cout << " try\n";
throw 10; // int
cout << " ";
}
catch ( int i ) { // int
cout << " ";
cout << i << "\n";
}
cout << " ";
}
8.1. .

8.1 :

try
10

,
try. 8.2 , -
catch -
.
#include <iostream.h>
#include <string.h>

// " "
class CExceptionMsg {
public:
CExceptionMsg( char* sMsg )
{ msg = new char[strlen( sMsg )+1]; strcpy( msg, sMsg ); }
~CExceptionMsg()
{ delete msg; }
char* GetMsg()
{ return msg; }

private:
char* msg;
};

void func(int test)


{

73
if ( test == 0 )
throw " ";
if ( test == 2 )
throw new CExceptionMsg( "Exception Info: 2" );
throw test;
}

void main()
{
cout << "\n";
try {
func(0);
func(1);
func(2);
func(3);
}
catch (int i) {
cout << " : " << i << "\n";
}
catch(char *str) {
cout << " : " << str << "\n";
}
catch(CExceptionMsg* pEx) {
cout << " - : ";
cout << pEx->GetMsg() << "\n";
delete pEx;
}

cout << " ";


}
8.2. .

8.2 :

:

, catch -
. (,
) -
catch, :
catch(...) {
cout << " - .\n";
exit( 1 );
}

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

74
2.

:

// 1- :
int* pData = new int[10000];
if ( pData == NULL )
{
cout << " !\n";
exit(1);
}

// 2- :
//
int* pData = new int[10000];
if ( pData == NULL )
return -10;

// 3- : ,
int* pData = new int[10000];

// 4- :
int* pData = new int[10000];
if ( pData == NULL )
NoMemoryError();

// 5- : assert(),
//
//
int* pData = new int[10000];
assert( pData != NULL );

1- " " , ,
, . 5-
,
. -
.
2- " - " ,
"". ,
int func() ,
int
. , -
, .
.
.
3- " - -
" , , -
- .
4- " - " ,
. ,

. , -

75
,
, .
, -
rrno .
errno , , -
. ,
.

-
, ,
. :
1) "" .
. -
,
.
2) .
( ) -
.
. , -
"" ,
, -
. , -
( , -
). -
, -
, -
.

(run-time) -
. , -
, . , -

. ,
.
" " ( , "
" ++),
, .
,
,
-
.

3. RTTI
++ -
, .

, , -

76
. , -
. -
(Run-Time Type Information, RTTI)
. RTTI ,
, .
typeid.
,
typeinfo.h. typeid :
typeid(obj)
typeid(typename)
obj , -
. typename , (-
, int double).
typeid type_info,
. type_info
:
boot operator==(const type_info& obj);
boot operator!=(const type_info& obj);
const char* name();
== !=
.
typeid. name() .
typeid ,
,
. -
, . -
, .
.
typeid 8.3.

++ ( int). typeid
, , -
CBaseClass.
#include <iostream.h>
#include <typeinfo.h>

class CBaseClass {
virtual void f() {;}
};
class CDerivedl: public CBaseClass {
virtual void f() {;}
};
class CDerived2: public CBaseClass {
virtual void f() {;}
};

void main()
{
CBaseClass *p, base_obj;
CDerivedl obj1;
77
CDerived2 obj2;
int i = 5;
cout << " i - " << typeid(i).name() << '\n';
p = &base_obj;
cout << " " << typeid(*p).name() << '\n';
p = &obj1;
cout << " " << typeid(*p).name() << '\n';
p = &obj2;
cout << " " << typeid(*p).name() << '\n';
}

8.3. typeid.

8.3 :
i int
class CBaseClass
class CDerivedl
class CDerived2

4.
++ -
(, (CDerived2*)base_obj),
. dynamic_cast, const_cast,
reinterpret_cast static_cast.
dynamic_cast.
dynamic_cast -
, -
. dynamic_cast :
dynamic_st< >()
_ , .
, . ,
dynamic_cast
.
dynamic_cast -
. ,
D, D .
dynamic_cast D* *.
,
. dynamic_cast
* D*, , ,
, D.
dynamic_cast , ( )
( ) -
, . -
. -
dynamic_cast , -

78
. ,
bad_cast.
dynamic_cast 8.4.

#include <iostream.h>

class CBase {
public:
virtual void f() { cout << " CBase\n"; }
};

class CDerived: public CBase {


public:
void f() { cout << " CDerived\n"; }
};

void main()
{
CBase *bp, b_obj;
CDerived *dp, d_obj;
dp = dynamic_cast<CDerived*>(&d_obj);
if (dp)
{
cout << " CDerived* CDerived* \n";
dp->f();
}
else
cout << "\n";
cout << '\n';
bp = dynamic_cast<CBase*>(&d_obj);
if (bp)
{
cout << " CDerived* CBase* \n";
bp->f();
}
else
cout << "\n";
cout << '\n';
bp = dynamic_cast<CBase*>(&b_obj);
if (bp)
{
cout << " CBase* CBase* \n";
bp->f();
}
else
cout << "\n";
cout << '\n';
dp = dynamic_cast<CDerived*>(&b_obj) ;
if (dp)
cout << "\n";
else
cout << " CBase* CDerived* \n";
cout << '\n';
bp = &d_obj; // bp CDerived

79
dp = dynamic_cast<CDerived*>(bp);
if (dp)
{
cout << " bp CDerived* , .. bp "
" CDerived\n";
dp->f() ;
}
else
cout << "\n";
cout << '\n';
bp = &b_obj; // bp CBase
dp = dynamic_cast<CDerived*>(bp);
if (dp)
cout << "\n";
else
cout << " CDerived* , .. "
" CBase\n";
cout << '\n';
dp = &d_obj; // dp CDerived
bp = dynamic_cast<CBase*>(dp);
if (bp)
{
cout << " dp CBase* \n";
bp->f();
}
else
cout << "\n";
}
8.4. .

8.4 :
CDerived* CDerived*
CDerived
CDerived* CBase*
CDerived
CBase* CBase*
CBase
CBase* CDerived*
bp CDerived* , .. bp
CDerived
CDerived
CDerived* , ..
CBase
dp CBase*
CDerived

80
5.
1) , catch. -
8.1 catch double. ,
.
2) ? ?
try {
// ...
throw 'a';
// ...
}
catch (char*) {
// ...
}
3) 8.2,
.
4) divide(),
a b.
double divide(double a, double b)
{
//
return a/b;
}

. ,
.
5) typeid
. 8.3
BaseClass ( virtual
f()) , .
6) ?
cout << typeid( float ).name();
7) . , p
D2?
class B {
virtual void f() {;}
};
class D1 : public B {
void f() {;}
};
class D2 : public B {
void f() {;}
};
void main()
{
B* p;
...
}

8) . 7 , -
dynamic_cast , p -
obj , obj D2.

81
9. STL
1.
(, , ,
, , , , ) .
, -
. -
++ STL.
, , , -
(), , , .
STL (STL Standard Template Library,
)
Hewlett-Packard
Rensselaer Polytechnic Institute.
STL . -
STL ( -
-). ++
. ,
.
.
,
, -
. -
,
(, CList, CMap
CArray MFC).
STL . , -
, .
-
(, ),
.
.
,
STL , -
. -
, - -
. , -
, ,
.

2. STL
STL : ,
. ++ -
.
(containers) ,
. . , vector -

82
, queue , list -
. - . -
, ,
.
.
(algorithms) .
, , -
. -
(sequence), -
.
(iterators) ,
.
, .
find -
.
, -
. find -
. , find,
:
template<class InputIterator, class T>
InputIterator find( InputIterator first, InputIterator last,
const T& value )
{
for ( ; first != last; ++first )
if ( *first == value )
break;
return first;
}

, -
. 9.1
7 .
#include <iostream.h>
#include <algorithm> // STL

// " std"
// STL
using namespace std;

void main()
{
int data[100];
memset( data, 0, sizeof( data ) );
data[50] = 7;
int* where = find( data, data+100, 7 );
cout << *where << '\n';
}
9.1. find .

83
9.2 , -
. find() , -
9.1.
#include <iostream.h>
#include <algorithm>
#include <list>

using namespace std;

void main()
{
list<int> intList;
for ( int i = 0; i < 100; i++ )
intList.push_back( i );

list<int>::iterator where;
where = find( intList.begin(), intList.end(), 7 );
cout << *where << '\n';
}
9.2. find , .

3.
STL - .
.
, , -
, , -
.
, . -
(
). ,
( ).
, -
. , , -
, , .
NULL
. -
. , -
NULL, -
, .
++ , -
, .
, x 10 -
x (x+10), (x+10) .
(x+10) , , -
. -
. -
, , ,
.

84
, , -
, ( ++). -
, ,
. -
(*) , .
,
, , ""
. ,
( ).
begin(), , -
, end().

4. -
STL -
. for_each(), , -
, . 9.3
, for_each() -
.
#include <iostream.h>
#include <algorithm>
#include <list>

using namespace std;

void PrintElement( int value )


{
cout << " " << value << '\n';
}

void main()
{
list<int> intList;
for ( int i = 0; i < 100; i++ )
intList.push_back( i );
for_each( intList.begin(), intList.end(), PrintElement );
}
9.3. for_each - PrintElement.

STL -. -
, "-
" (). -. -
- ,
" ".
:
class BiggerThanThree {
public:
bool operator () (int v)
{ return v > 3; }
};

85
CBiggerThanThree, ,
, -
" ".
, , -
:
class CBiggerThan {
public:
CBiggerThan( int x ) : testValue(x) {;}
bool operator () (int val)
{ return val>testValue; }
const int testValue;
};

, -
" X", X
. -
STL, , find_if.

12:
list<int>::iterator firstBig = find_if( intList.begin(),
intList.end(),
CBiggerThan(12) );

5. :
, -
STL. , -
. - , -
:
class CWidget
{
public:
CWidget(int a) : id(a) {}
CWidget() : id(0) {}
int id;
};

-
:
bool operator== ( const CWidget& lhs, const CWidget& rhs )
{
return lhs.id == rhs.id;
}
bool operator!= ( const CWidget& lhs, const CWidget& rhs )
{
return lhs.id != rhs.id;
}
bool operator< ( const CWidget& lhs, const CWidget& rhs )
{
return lhs.id < rhs.id;

86
}
bool operator> ( const CWidget& lhs, const CWidget& rhs )
{
return lhs.id > rhs.id;
}

. -
, . ,
. ,
.
-:
Order() ;
Receive() .
class CInventory
{
public:
void Order( int wid ); // wid
void Receive( int wid ); // wid

private:
list<CWidget> on_hand;
list<int> on_order;
};

,
. find() -
. , -
. .
void CInventory::Receive( int wid )
{
cout << " " << wid << endl;
list<int>::iterator weNeed = find( on_order.begin(),
on_order.end(), wid );
if ( weNeed != on_order.end() )
{
cout << " " << wid << " \n";
on_order.erase(weNeed);
}
else
on_hand.push_front( CWidget(wid) );
}

,
find_if() , ,
. , -
,
. :
class CWidgetTester {
public:
CWidgetTester( int t ) : testid(t) { }
bool operator() ( const CWidget& wid )

87
{ return wid.id == testid; }
const int testid;
};

, , :
void CInventory::Order( int wid )
{
cout << " " << wid << endl;
list<CWidget>::iterator weHave = find_if( on_hand.begin(),
on_hand.end(), CWidgetTester(wid) );
if ( weHave != on_hand.end() )
{
cout << " " << weHave->id << endl;
on_hand.erase(weHave);
}
else
{
cout << " " << wid << endl;
on_order.push_front(wid);
};
}

CInventory, -
, :
void main()
{
CInventory inv;
inv.Receive( 5 );
inv.Order( 10 );
inv.Order( 5 );
inv.Receive( 10 );
inv.Receive( 10 );
}

6.
STL .
map, -
. -
, . -
, , -
/. -
. ,

, .
. -
.
- multimap.
/
pair. :
template <class Ktype, class Vtype> struct pair {

88
Ktype first; //
Vtype second; //
//
pair();
pair( const Ktype& k, const Vtype& v );
}
9.4 ,
/ :
A 0
B 1
C 2
...
J 9
( A J)
.
-
find(). ,
, .
#include <iostream>
#include <map>
using namespace std;

void main()
{
map<char, int> m;
// /
for ( int i = 0; i < 10; i++ )
m['A'+i] = i;

char ch;
cout << " : ";
cin >> ch;

map<char, int>::iterator p;

//
p = m.find( ch );
if ( p != m.end() )
cout << p->second;
else
cout << " \n";
}
9.4. .

STL, -
. 9.5 ,
.
STL string. (, +, -, ==), -
(, -
s1==s2, strcmp(s1, s2)). 9.5 -
( -
). find()
map [].

89
#include <iostream>
#include <map>
#include <string>
#pragma warning( disable : 4786 )
using namespace std;

void main()
{
map<string, string> m;
m["yes"] = "no";
m["good"] = "bad";
m["left"] = "right";
m["up"] = "down";

//
string str;
cout << " : ";
cin >> str;

if ( m[str] != "" )
cout << ": " << m[str];
else
cout << " \n";
}
9.5. .

7.
1) 9.1, 9.2 9.3 , , .
2) .5 .
algorithm list.
3) 9.5
.
, -
.

90

1) . - . .: ,
1999. ( , ,
. -
.
++ Java.)
2) . - .
.: , 1992. ( - -
-
. ,
, -
.)
3) . + = . .: , 1985. (-
.
.)
4) . ++. . .:"",
1993. ( ++, .
,
.)
5) . ++. .: BHV-, 2000. (
++.
, .)

91
-

.. , ..

++
4- .
( -
)

..
..
12.04.2002 16.04.2002
60841/16
. . 20,5 -.. ____ 100
06076 19.10.2001

140410 ., .., ., 30. -


.

92
93

Оценить