Polynomial::~Polynomial()
{
delete [] this->m_Ptr;
this->m_Ptr = NULL;
}
Polynomial::Polynomial(int size)
{
this->size = size;
this->m_Ptr = newdouble[this->size];
}
Polynomial::Polynomial(const Polynomial &other)
{
//Perform a deep copy
this->size = other.size;
//this->m_Ptr = new double[this->size];
}
const Polynomial Polynomial::operator +(const Polynomial &other) const
{
const Polynomial * result = this;
for (int i = 0; i < other.size; i++)
{
*(result->m_Ptr + i) = *(other.m_Ptr + i) + *(this->m_Ptr + i);
}
return *(result);
}
const Polynomial Polynomial::operator -(const Polynomial &other) const
{
const Polynomial * result = this;
for (int i = 0; i < other.size; i++)
{
*(result->m_Ptr + i) = *(other.m_Ptr + i) - *(this->m_Ptr + i);
}
return *(result);
}
const Polynomial Polynomial::operator *(const Polynomial &other) const
{
const Polynomial * result = this;
for (int i = 0; i < other.size; i++)
{
*(result->m_Ptr + i) = *(other.m_Ptr + i) * *(this->m_Ptr + i);
}
return *(result);
}
std::ostream& operator <<(std::ostream &outputStream, const Polynomial &other)
{
int n = other.size;
for (int i = 0; i < other.size; i++)
{
if (*(other.m_Ptr + i) == 0)
{
n--;
continue;
}
if (n > 0)
{
outputStream << *(other.m_Ptr + i) << "x^" << n << " ";
}
else
{
outputStream << *(other.m_Ptr + i);
}
n--;
}
return outputStream;
}
std::istream& operator >>(std::istream &inputStream, const Polynomial &other)
{
for (int i = 0; i < other.size; i++)
{
inputStream >> *(other.m_Ptr + i);
}
return inputStream;
}
What works:
Adding two pointers. The output is correctly produced.
The problems:
The problem in particular occurs in main when p1 and p2 are attempted to be multiplied. The code attempts to release the memory upon multiplication but I receive a run-time error.
The output for the difference of the two polynomial objects is incorrect. It is displaying addresses.
OK. I removed * from p1 and p2 in main and the memory is able to release on from multiplying.
Quick question: how would I use a deep copy if I am allocating in the constructor?
If I choose to move the allocation from the ctor to the copy ctor, my << overload goes a little haywire. I then applied indexing to the pointer but it still proves problematic.
If you don't use pointers, you don't have to worry about this craziness.
lampshader wrote:
Quick question: how would I use a deep copy if I am allocating in the constructor?
It doesn't matter where the allocation occurs. You need to implement your own copy constructor and copy assignment operator because you are using pointers.
lampshader wrote:
If I choose to move the allocation from the ctor to the copy ctor, my << overload goes a little haywire. I then applied indexing to the pointer but it still proves problematic.