// ( c3.C ) // 派生クラスの例−その3 // #include class Vector { int x,y ; public: Vector( int a=0,int b=0 ) { x = a ; y = b ; } } ; class Base { public: virtual void show_color() = 0 ; // 仮想メンバ関数と言う } ; // = 0 と定義するのを、特に純粋仮想関数と言う class Point: public Base { // 基底クラス Base に対して、派生クラス Point Vector pt ; // と言う int color ; public: Point( int a=0,int b=0,int cc=0 ):pt( a,b ) { color = cc ; } void show_color() { cout << "Point Color = " << color << "\n" ; } } ; class Line: public Base { Point p1,p2 ; int color ; int ltype ; // クラス Line に線種の項目を追加する public: Line() { p1 = Point() ; p2 = Point() ; color = 0 ; ltype = 0 ; } Line( int x1,int y1,int x2,int y2,int cc=0,int type=0 ):p1(x1,y1),p2(x2,y2) { color = cc ; ltype = type ; } void show_color() { cout << "Line Color = " << color << "\n" ; } int& get_ltype() { return ltype ; } } ; // 注目、アドレスを返す方が効率がよい void all_color( Base* lp[] ) { for ( int i=0;lp[i] != NULL ;i++ ) cout << "Line_Type : " << ( (Line*)lp[i] )->get_ltype() << "\n" ; } main() { Base* List[4] ; Line l1 ; List[0] = &l1 ; Line l2( 1,2,3,4, 1,1 ) ; List[1] = &l2 ; Line l3( 5,6,7,8, 1,2 ) ; List[2] = &l3 ; List[3] = NULL ; Line* temp ; temp = (Line*)List[0] ; // Line* temp = (Line*)List[0] でもよい cout << temp->get_ltype() << "\n" ; cout << ( (Line*)List[1] )->get_ltype() << "\n" ; all_color( List ) ; } /* [結果] クラス Base の List[] というのは、Point や Line などのデ−タ 0 を蓄える汎用的な配列と考えられる。この配列から直接参照できる 1 のは show_color() 関数だけであり Line の線種は参照できない。 Line_Type = 0 このためクラス Base からクラス Line に変換して参照する。 Line_Type = 1 Line_Type = 2 ( (Line*)List[1] )->get_ltype() ; (Line*) が変換している */