.


:




:

































 

 

 

 





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

#include "iostream.h"

#include "string.h"

template <class T>

struct Status //

{ T *RealPtr; //

int Count; //

};

template <class T>

class Point // -

{ Status<T> *StatPtr;

public:

Point(T *ptr=0); //

Point(const Point &); //

~Point();

Point &operator=(const Point &); //

// Point &operator=(T *ptr); //

T *operator->() const;

T &operator*() const;

};

Point . NULL, Status, , NULL. Status

template <class T>

Point<T>::Point(T *ptr) //

{ if(!ptr) StatPtr=NULL;

else

{ StatPtr=new Status<T>;

StatPtr->RealPtr=ptr;

StatPtr->Count=1;

}

}

StatPtr , , .

template <class T> //

Point<T>::Point(const Point &p):StatPtr(p.StatPtr)

{

if(StatPtr) StatPtr->Count++; //

}

1, 0

template <class T>

Point<T>::~Point() //

{ if(StatPtr)

{ StatPtr->Count--; //

if(StatPtr->Count<=0) // <=0,

{ delete StatPtr->RealPtr; //

delete StatPtr;

}

}

}

template <class T>

T *Point<T>::operator->() const

{ if(StatPtr) return StatPtr->RealPtr;

else return NULL;

}

template <class T>

T &Point<T>::operator*() const // StatPtr

{ if(StatPtr) return *StatPtr->RealPtr; // this-

else throw bad_pointer; //

}

= , =.

template <class T>

Point<T> &Point<T>::operator=(const Point &p)

{ // =

if(StatPtr)

{ StatPtr->Count--;

if(StatPtr->Count<=0) //

{ delete StatPtr->RealPtr; //

delete StatPtr; //

}

}

//

StatPtr=p.StatPtr;

if(StatPtr) StatPtr->Count++;

return *this;

}

Struct Str

{ int a;

char c;

};

void main()

{ Point<Str> pt1(new Str); // Point,

// pt1,

// - Str, -

//

Point<Str> pt2=pt1,pt3; // pt2 ,

// pt3

pt3=pt1; // pt3 pt1

(*pt1).a=12; // operator*() this pt1

(*pt1).c='b';

int X=pt1->a; // operator->() this- pt1

char C=pt1->c;

}

 

 

1. .

2. [1,2,3,4,5].

3. .

4. , .

 

 

1. . \ . [] . .

2. . \ . >, < . .

3. . . .

4. . . .





:


: 2016-12-06; !; : 366 |


:

:

,
==> ...

1657 - | 1632 -


© 2015-2024 lektsii.org - -

: 0.009 .