// ( o5.C ) // 異種のオブジェクトをポインタで関連付ける // #include // 問題:1個の円筒を考える。その2面図として、円と線 // 分が2本ある。円の径を変えると線分の位置も変わり、 class Line ; // その逆もできる操作を考える。 class Circle { Line* p1 ; // コンピュ−タの中に、円と線分がふわふわと浮いていて Line* p2 ; // 円の径を外から変更すると、円があたかも線分に対して int radius ; // おまえもデ−タを変更しろと言っているかの様に見える。 public: Circle( int r ) { radius = r ; } void set( Line* a1,Line* a2 ) { p1 = a1 ; p2 = a2 ; } int get_radius() { return radius ; } void change_radius( int r ) ; } ; // ふわふわと浮いていていると想像すれば、Circle,Line class Line { // のインスタンスがオブジェクトだな−と思えるのでは。 Circle* cc ; int sx ; public: Line( int x ) { sx = x ; } void set( Circle* c ) { cc = c ; } void change_sx( int i ) { sx = i ; } void move_line( int i ) ; int get_sx() { return sx ; } } ; // 注意:クラスの定義はこの順番にしなければならない。 void Circle::change_radius( int r ) { radius = r ; p1->change_sx( r/2 ) ; p2->change_sx( -r/2 ) ; } void Line::move_line( int i ) { sx = i ; cc->change_radius( i*2 ) ; } main() { Circle* d = new Circle(10); // 中心のY座標0とする直径10の円 Line* e1 = new Line(5) ; // 円の上下の線分を定義する Line* e2 = new Line(-5) ; d->set( e1,e2 ) ; // 円には2本の線分が関連している e1->set( d ) ; // それぞれの線分は円に関連している e2->set( d ) ; d->change_radius( 20 ) ; // 円の径を変更してみる cout << "Radius : " << d->get_radius() << endl ; cout << e1->get_sx() << "," << e2->get_sx() << endl ; e1->move_line( 20 ) ; // 線分の位置を変更してみる cout << "Radius : " << d->get_radius() << endl ; cout << e1->get_sx() << "," << e2->get_sx() << endl ; delete d ; delete e1 ; delete e2 ; } /* [結果] Radius : 20 10,-10 Radius : 40 20,-20 */