// shape.cpp // Implementation of classes Shape and Polyline. #include "shape.h" // class Shape // all methods inline // class Polyline Polyline::Polyline( Point arr[], int n ) { arrPoints = NULL; nLines = 0; if( n > 0 ) { anchor = arr[ 0 ]; // anchor if( n > 1 ) { nLines = n - 1; // save points relatively to anchor arrPoints = new Point[ nLines ]; for( int i = 0; i < n-1; ++i ) arrPoints[ i ] = arr[ i + 1 ] - anchor; } } } Polyline::Polyline( const Polyline& src ) // copy constructor { nLines = src.nLines; anchor = src.anchor; arrPoints = NULL; if( src.nLines > 0 ) { arrPoints = new Point[ nLines ]; for( int i = 0; i < nLines; ++i ) arrPoints[ i ] = src.arrPoints[ i ]; } } Polyline& Polyline::operator=( const Polyline& src ) // assignment { if( this != &src ) { delete [] arrPoints; nLines = src.nLines; anchor = src.anchor; arrPoints = NULL; if( src.nLines > 0 ) { arrPoints = new Point[ nLines ]; for( int i = 0; i < nLines; ++i ) arrPoints[ i ] = src.arrPoints[ i ]; } } return *this; } double Polyline::getLength() const { double len = 0.0; if( nLines > 0 ) { Point begin( 0, 0 ); for( int i = 0; i < nLines; ++i ) { len += begin.distance( arrPoints[ i ] ); begin = arrPoints[ i ]; } } return len; } // append one more point: Polyline& Polyline::operator+=( const Point& p ) { Point* ptr = new Point[ nLines + 1 ]; // new array for( int i = 0 ; i < nLines; ++i ) // copy points into new array ptr[ i ] = arrPoints[ i ]; ptr[ nLines ] = p - anchor; // add new point ++nLines; delete [] arrPoints; // free old array arrPoints = ptr; return *this; } // append a second line: Polyline& Polyline::operator+=( const Polyline& src ) { if( src.nLines > 0 ) { Point last = Point( 0, 0 ); // rel. coordinates of last point if( nLines > 0 ) last = arrPoints[ nLines - 1 ]; Point* ptr = new Point[ nLines + src.nLines ]; // new array int i; for( i = 0; i < nLines; ++i ) // copy points into new array ptr[ i ] = arrPoints[ i ]; for( i = 0; i < src.nLines; ++i ) // append points of src ptr[ nLines + i ] = last + src.arrPoints[ i ]; nLines += src.nLines; delete [] arrPoints; // free old array arrPoints = ptr; } return *this; } void Polyline::scale( double scalingFactor ) { for( int i = 0; i < nLines; ++i ) arrPoints[ i ] *= scalingFactor; } string Polyline::toString() const // points of line { string str = anchor.toString(); for( int i = 0; i < nLines; ++i ) str += " ", str += ( anchor + arrPoints[ i ] ).toString(); return str; }