// ( c1.C ) // 派生クラスの例−その1 // #include class Vector { // 基底クラス(ベ−スクラスとも言う) int x,y ; // 座標値のみをもっているクラス public: Vector( int a,int b ) { x = a ; y = b ; } int get_x() { return x ; } } ; class Point: public Vector { // 派生クラス(導出クラスとも言う) int color ; public: // デフォルトの色は9 Point( int a,int b,int cc=9 ):Vector( a,b ) { color = cc ; } int get_color() { return color ; } } ; class Line { Point p1,p2 ; int type ; public: Line( int x1,int y1,int x2,int y2,int t ):p1(x1,y1),p2(x2,y2) { type = t ; } int get_type() { return type ; } Point get_p1() { return p1 ; } } ; // const Point& get_p1() { return p1 ; } でもよい /* Line の定義を外で行う方法(むしろこっちが一般的) class Line { Point p ; 中味をちょっと省略しました public: Line( int x1,int y1,int x2,int y2,int t ) ; } ; Line::Line( int x,int y ):p(x,y) {} 普通このように外では中味を定義する。 inline Line::Line( int x,int y ):p(x,y) {} inline 指定すると中で定義したのと同じ ことになる。小さいル−チンは inline 指定した方が、実行速度が上がる。 */ main() { Point a( 100,200,2 ) ; // get_x() は Vector クラスの中で定義されている cout << "P-xcoor : " << a.get_x() << "\n" ; cout << "P-color : " << a.get_color() << "\n" ; Line b( 10,20,30,40,1 ) ; // Line の色は Point クラスのデフォルトで9になる cout << "L-xcoor : " << b.get_p1().get_x() << "\n" ; cout << "L-color : " << b.get_p1().get_color() << "\n" ; } /* [結果] P-xcoor : 100 P-color : 2 L-xcoor : 10 L-color : 9 */