// ( c6.C ) // コンストラクタの検討−Line( const Point& a ) の場合 // #include // const Point& a の const も安全のため付けてある。 // Line(const Point a) より、こっちの定義を勧める。 class Point { int x; int flag ; public: Point( int x1=0 ) { x = x1 ; flag = 0 ; cout << "make Point" <<"\n"; } ~Point() { x = 0 ; cout << "del Point : " << flag << endl ; } // 以下暗黙の定義を明示して記述した Point( const Point& p ) { x = p.x ; flag = 1 ; cout << "copy make Point" <<"\n"; } const Point& operator=( const Point& p ) { x = p.x ; cout << "operator =\n" ; return *this ; } void show() { cout << x << endl ; } }; class Line { // 2つのコンストラクタの記述方法:どちらでも構わない! Point p ; public: // Line( const Point& a ) { p = a ; cout << "make Line" <<"\n"; } Line( const Point& a ):p(a) { cout << "make Line" <<"\n"; } ~Line() { cout << "del Line\n" ; } void show() { p.show() ; } }; main() { Point a( 10 ); Line b( a ); /* Point* a = new Point( 10 ); // 参考です a->show() ; // 10 Line b( *a ); delete a ; b.show() ; // 10 Line の中の Point は外の a とは別物である。 */ } /* [結果] make Point 検討1:Line( Point& a ) { p = a ; make Point (operator =) make Line del Line del Point : 2 del Point : 0 make Point 検討2: Line( Point& a ):p(a) copy make Point make Line del Line del Point : 1 del Point : 0 */