Reputation: 49
I am writing a program to implement a linked list. The list contains nodes that are used to represent terms in a polynomial function. I have a class called Polynomial
where I instantiate the linked list. The class has methods that allow you to modify the polynomial, including an addTerm method.
In my main, I would like to do something like this:
Polynomial p, q;
p.addTerm({ 4, 8 });
p.addTerm({ -3, 2 });
q = p;
p.addTerm({ 5, 6 });
p.addTerm({ 3, 2 });
this is the full Polynomial class:
class Polynomial {
Node* Head;
public:
Polynomial();
~Polynomial();
void addTerm(Term term);
unsigned int degree() const;
double coefficientFor(unsigned int exponent) const;
void clear();
private:
void DeleteInvalidNode();
};
and the constuctor:
Polynomial::Polynomial()
{
Head = 0;
}
For some reason, though, when I add the terms to p
after copying p
to q
it adds those terms to q
. From what I understand this is because when you copy an object to another object they point to the same thing. Is there any way that I can fix this to where when I modify p
it doesnt effect q
EDIT: I have now made an operator copy assignment function to try and copy the linked list.
I have written the following:
Polynomial& Polynomial::operator=(const Polynomial& rhs)
{
Node* Temp = rhs.Head;
while (rhs.Head != NULL)
{
Temp = rhs.Head->next;
this->addTerm({ rhs.coefficientFor(degree()), rhs.degree() });
rhs.Head = Temp;
}
return *this;
}
It is not working though since rhs is constant and I am trying to modify it. I am very new to linked lists. How would I go about fixing this to where it can work?
Upvotes: 2
Views: 498
Reputation: 104
This is likely due to how you define the "=" operator in the Polynomial
class. In here, you have to make sure that it's creating new copies of the terms rather than pointing to the contents of the other Polynomial
object.
Make the following function a public
function in Polynomial
:
Polynomial& operator=(const Polynomial& rhs){
/*Not sure the specifics of your functions or the intention of Nodes, so
if you need to iterate throuch each term in a Polynomial, be sure to do so,
and put the statement below within your loop.*/
this->addTerm({rhs->coefficientFor(rhs->degree()),rhs->degree()});
/*or something to that effect, what matters is being able to retrieve the
each Term in the rhs (right-hand-side) and adding them to this
Polynomial.*/
return this*;
Upvotes: 2