// ( o7.C ) // オブジェクト指向におけるデ−タ構造の一形態 // $ cpc o7;CC -o o7 o7.o o6s.o -O -v /*------------------------------------------------------------------------ リスト EList には Point オブジェクトのポインタを入れていく。 個々の Point オブジェクトは、リストへのポインタを内部に持つ。 Point 自身を自分自身の命令によって消去し、さらに自動的にリス トに登録した情報も消去することを考える。 --------------------------------------------------------------------------*/ #include #include "o6.h" class EList: public List { // とりあえず List を使う public: void Report() ; } ; class Point { static EList* dbase ; // EList へのポインタを保持する int x,y; public: Point( int xx,int yy ) { x = xx ; y = yy ; } ~Point() { cout << "delete Point\n" ; dbase->Del( this ) ; } // 注目! 自分で自分を消してしまう命令 void del_self() { delete this ; } void display() { cout << x << ","<< y << endl ; } } ; void EList::Report() { Node *Current = SNode ; while ( Current->Next != NULL ) { Point* temp = (Point*)Current->Item ; temp->display() ; Current = Current->Next ; } } EList* list = new EList() ; EList* Point::dbase = list ; main() { Point a( 1,1 ) ; list->Add( &a ) ; Point b( 2,2 ) ; list->Add( &b ) ; Point* c = new Point( 3,3 ) ; list->Add( c ) ; Point* d = new Point( 4,4 ) ; list->Add( d ) ; c->del_self() ; // 自分自身を消去する // Point のデストラクタが働く list->Report() ; } /* [結果] delete Point 1,1 2,2 4,4 */