The assignment is to make a linked list class that represents a polynomial. Each node represents one term. Then we have to overload the + operator in order to do the sum of two polynomial. I also overloaded the = operator to create a deep copy of a polynomial and the << operator to display the polynimial.

My probem is within the + operator. This is my code:

Poly Poly::operator+(const Poly& orig)

{

Poly n;

polyTerm* cur;

polyTerm* cur2;

cur=head;

cur2=orig.head;

//Add all the terms from the Left Hand polynomial

while(cur != NULL)

{

n.newterm(cur->exponent, cur->coefficient);

cur = cur->next;

}

//Add all the terms from the Right Hand polynomial

while(cur2 != NULL)

{

n.newterm(cur2->exponent, cur2->coefficient);

cur2 = cur2->next;

}

n.sort(); //sort terms in descending order of exponents

n.simplify();//combine terms with equal exponents into a single term by addition

cout<<"\nFinal sum is: "<<endl<<n;

return n;

}

The line right above the return proves that the operation has succeeded since it displays the correct polynomial. However, in the main function when I do sum=Poly1+Poly2,and cout<<sum it displays only the first term of the sum polynomial.

After investigation I think the problem comes from the " return n" in the + overloading.

Could anyone help me find the problem please ?

My probem is within the + operator. This is my code:

Poly Poly::operator+(const Poly& orig)

{

Poly n;

polyTerm* cur;

polyTerm* cur2;

cur=head;

cur2=orig.head;

//Add all the terms from the Left Hand polynomial

while(cur != NULL)

{

n.newterm(cur->exponent, cur->coefficient);

cur = cur->next;

}

//Add all the terms from the Right Hand polynomial

while(cur2 != NULL)

{

n.newterm(cur2->exponent, cur2->coefficient);

cur2 = cur2->next;

}

n.sort(); //sort terms in descending order of exponents

n.simplify();//combine terms with equal exponents into a single term by addition

cout<<"\nFinal sum is: "<<endl<<n;

return n;

}

The line right above the return proves that the operation has succeeded since it displays the correct polynomial. However, in the main function when I do sum=Poly1+Poly2,and cout<<sum it displays only the first term of the sum polynomial.

After investigation I think the problem comes from the " return n" in the + overloading.

Could anyone help me find the problem please ?

Last edited on

You didn't provide a copy constructor

http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29

`Poly::Poly(``const` Poly& original)

, so it makes an shallow copy. You also should write destructor.http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29

Last edited on

Topic archived. No new replies allowed.