/////// File: Poly.C /////// #include #include "Poly.h" #define MAX(x,y) ((x) > (y) ? x : y) Poly::Poly(const int *p, int n) // p supplies n terms : pol( n > 0 ? new int[*p+2] // initialize pointer pol : new int ) { if ( n == 0 ) *pol = -1; // zero polynomial else s_to_d(pol, p); // converted data in pol } Poly::Poly() // default constructor : pol ( new int[2] ) { pol[0] = 0; pol[1] = 0; } // sparse to dense conversion void Poly::s_to_d(int *buf, const int *p) { int d = *buf++ = s_deg(p); if (*p == -1) { *buf = 0; return; } while ( d >= 0 ) { if ( d == *p ) { *buf++ = *++p; p++; } else /* ( d > *p ) */ { *buf++ = 0; } d--; } } Poly Poly::operator+(const Poly& q) const { int *c, *a, *b; Poly ans; // result object int d = deg(), dq = q.deg(); if ( d < dq ) { dq = d; d = q.deg(); b = pol; a = q.pol; // d=deg(a) >= deg(b) } else { a = pol; b = q.pol; } a++; b++; while ( d == dq && d > 0 && *a + *b == 0 ) // leading terms cancel { d--; dq--; a++; b++; } ans.pol = c = new(int[d+2]); // allocate space for result *c++ = d; // degree of result while(d-- > dq) *c++ = *a++; // leading terms while(d-- > -2) *c++ = *a++ + *b++; // add terms return(ans); } void Poly::display() { int *p = pol + 1; int d = deg(), e = d; cout << '('; while ( d >= 0 ) { if (*p != 0 || d == 0) { if ( d < e ) cout << ", "; cout << d << " " << *p; } d--; p++; } cout << ")\n"; } Poly& Poly::operator =(const Poly& p) { if ( this == &p) return(*this); unsigned pd = p.deg(); if ( deg() < pd ) { delete [] pol; pol = new int[pd + 2]; } for (int i=0 ; i < pd + 2 ; i++) pol[i] = p.pol[i]; cout << "= called" << endl; return(*this); } Poly::Poly(const Poly& p) : pol(new int[p.deg() + 2]) { for (int i=p.deg()+1 ; i > -1 ; i--) pol[i] = p.pol[i]; cout << "copy constructor called" << endl; }