All pastes #925539 Raw Edit

Polynomial.C

public text v1 · immutable
·published 2008-03-03 02:44 UTC
rendered paste body
#include <iostream>
#include "Polynomial.h"

/*
	Default constructor.
	initiates the int deg to ?
	initiates the int* coef to ? 
*/
Polynomial::Polynomial()
{
	this->deg = 0;
	this->coef = NULL;
}


/*
	Defined constructor.
	initiates the int deg to input deg
	initiates the int* coef to input coef
*/
Polynomial::Polynomial(int deg, int* coef)
{
	this->deg = (int) deg;
	this->coef = new int [deg + 1];
	for(int i = 0; i < (deg + 1); i++)

  	{

    		this->coef[i] = coef[i];

  	}
}


/*
	Copy constructor.
	Creates a Deep Copy of the provided 
	Polynomial
*/
Polynomial::Polynomial(const Polynomial& p)
{
	//Polynomial(p.deg, p.coef);
	// ^ this won't work for some 
	// reason.  It causes a core dump.
	this->deg = (int) p.deg;
	this->coef = new int [p.deg + 1];
	for(int i = 0; i < (p.deg + 1); i++)

  	{

    		this->coef[i] = p.coef[i];

  	}
  	// ^ this works.  
  	// The confusion:
  	//   if the code being run is the same
  	//   and the only difference is
  	//   the fact that the variables
  	//   are passed as parameters twice
  	//   in one and once in the other,
  	//   why does one work and the other
  	//   causes a core dump? 
}


/*
	Destructor.
	This method runs when a 
	Polynomial leaves scope.
*/
Polynomial::~Polynomial()
{
	delete [] coef;
	//delete deg;
}


/*
	Assignent operator override.
	This method will allow the
	setting of one Polynomial
	to another Polynomial.
	It does not create references
	but Deep Copies of the input
	polynomial.
*/
Polynomial& Polynomial::operator=(const Polynomial& p)
{
	deg = (int) p.deg;
	for(int i = 0; i < (deg + 1); i++)

  	{

    		coef[i] = (int) p.coef[i];

  	}
	return *this;
}


/*
	
*/
ostream& operator<<(ostream& out, const Polynomial& p)
{
	out <<"p(x) = ";
	for (int i = (p.deg); i >= 0; i--)
	{	
		if (p.coef[i] < 0)// negative coefficient
		{
			out << "- " <<(p.coef[i] * -1);
		}
		else // positive coefficient
		{
			if (i != (p.deg))// not the first element
			{
				out << "+ " <<p.coef[i];
			}
		}

		if (i != 0)
		{
			if (i != 1)
				out << "x^" << i << " ";
			else
				out << "x ";
		}
	}
	return out;
}