// ( c12.C ) // 仮想関数:基底クラスの余分な要素 // #include // 一応 color は Base クラスの方に入れた。しかし Base の // 中の type って何なのだ。Pointx に共通なものではないし、 // 区別するために仕方なしに入れているのだ。邪魔だからとっ // てしまいたい。 const int POINT1_ID = 1 ; // #define 定義を const に変更した。 const int POINT2_ID = 2 ; // C++では定数定義は const を使う。 class Base { protected: int color ; public: int type ; } ; class Point1: public Base { public: Point1() { color = 1 ; type = POINT1_ID ; } void show_color() { cout << "Point1 Color = " << color << endl ; } } ; class Point2: public Base { public: Point2() { color = 2 ; type = POINT2_ID ; } void show_color() { cout << "Point2 Color = " << color << endl ; } } ; main() { Base* List[3] ; Point1* p1 = new Point1() ; List[0] = p1 ; Point2* p2 = new Point2 ; List[1] = p2 ; // Point2() でも Point2 でも、 // この場合はよい List[2] = NULL ; for ( int i=0;List[i] != NULL;i++ ) { if ( List[i]->type == POINT1_ID ) ((Point1*)List[i])->show_color() ; else if ( List[i]->type == POINT2_ID ) ((Point2*)List[i])->show_color() ; } delete p1 ; delete p2 ; }