// ( o9.C ) // 関連付けられたオブジェクトの管理 // #include class Line ; // 問題:線分は2個の点からなり、それぞれ互いに // ポインタ−で関連付けられているという前提。 class Point { Line* lp ; // Line オブジェクトのアドレスを保持するポインタ int x,y; public: Point( int xx,int yy ) { x = xx ; y = yy ; lp = NULL ; } ~Point() ; void set_line( Line* l ) { lp = l ; } void display() { cout << x << ","<< y << " " ; } void infor() { if ( lp == NULL ) cout << "Line Object not connect\n" ; else cout << "Line Object connect\n" ; } } ; class Line { Point *p1,*p2; // Point オブジェクトのアドレスを保持するポインタ public: Line( Point* a,Point* b ) { p1 = a ; p1->set_line( this ) ; p2 = b ; p2->set_line( this ) ; } ~Line() { if ( p1 != NULL ) p1->set_line( NULL ) ; if ( p2 != NULL ) p2->set_line( NULL ) ; cout << "delete Line Object\n" ; } void display() { cout <<"LINE data : " ; if ( p1 != NULL ) p1->display() ; if ( p2 != NULL ) p2->display() ; cout << endl ; } void del_point( Point *p ) { // Point オブジェクトの情報を消去する if ( p == p1 ) p1 = NULL ; else if ( p == p2 ) p2 = NULL ; } } ; // ここで定義しないとエラ−になる Point::~Point() // error: member del_point undefined { if ( lp != NULL ) lp->del_point( this ) ; cout << "delete Point Object\n" ; } main() { Point* pa = new Point( 1,1 ) ; Point* pb = new Point( 5,5 ) ; Line* la = new Line( pa,pb ) ; la->display() ; // LINE data : 1,1 5,5 delete pa ; // delete Point Object la->display() ; // LINE data : 5,5 delete la ; // delete Line Object pb->infor() ; // Line Object not connect }