// ( c11.C ) // 仮想関数:よくない基底クラス // #include // 2個の Pointx は共通な性質として、色の color をもって // いる。ならば color は基底クラスに含めるべきじゃないか。 #define POINT1_ID 1 #define POINT2_ID 2 class Base { // これは一体どういう基底クラス。性格がはっきりしない public: int type ; } ; class Point1: public Base { // クラス Base の派生クラス Point1 int color ; public: Point1() { color = 1 ; type = POINT1_ID ; } void show_color() { cout << "Point1 Color = " << color << endl ; } } ; class Point2: public Base { // クラス Base の派生クラス Point2 int color ; 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 ; // れると考えてよい List[2] = NULL ; for ( int i=0;List[i] != NULL;i++ ) { if ( List[i]->type == POINT1_ID ) // 基底クラスで type を判別する ((Point1*)List[i])->show_color() ; // それぞれのクラスのポインタを else if ( List[i]->type == POINT2_ID ) // 引き出して、関数を呼びださな ((Point2*)List[i])->show_color() ; // ければならない } delete p1 ; delete p2 ; } /* [結果] Point Color = 1 Point Color = 2 */