每当调用multiply方法时,下一个指针永远不会更新并指向自身,即使程序工作并正确地更新所有内容 .
#include <iostream>
using namespace std;
class Term{
public:
Term(int c, int p);
Term(const Term &t2);
Term* next;
int coefficient, power;
friend class Polynomial;
};
Term::Term(const Term &t2){
this->coefficient = t2.coefficient;
this->power = t2.power;
this->next = t2.next;
}
Term::Term(int c, int p){
coefficient = c;
power = p;
next = NULL;
}
class Polynomial{
public:
Polynomial(Term t);
void add(Polynomial p);
void print();
Term* poly;
Polynomial multiply(Polynomial p);
};
Polynomial::Polynomial(Term t){
poly = &t;
}
Polynomial Polynomial::multiply(Polynomial p){
Polynomial temp (Term(0,0));
Term* temp1 = poly;
Term* temp2 = p.poly;
while (temp1 != NULL){
while(temp2 != NULL){
int p = temp1->power + temp2->power;
int c = temp1->coefficient * temp2->coefficient;
temp.add(Polynomial(Term(c, p)));
temp2=temp2->next;
}
temp1 = temp1->next;
}
cout << temp.poly;
// temp.print();
return temp;
}
void Polynomial::add(Polynomial p){
p.poly->next = poly;
poly = p.poly;
}
void Polynomial::print(){
Term* temp = poly;
while(temp != NULL){
if (temp->coefficient!=0){
cout << temp->coefficient << "*x^" << temp->power;
if(temp->next != NULL) cout << " + ";
}
temp = temp->next;
}
}
int main(){
Polynomial p (Term(-10,0));
p.add(Polynomial (Term(-1,1)));
p.add(Polynomial (Term(9,7)));
p.add(Polynomial (Term(5,10)));
Polynomial pp = p.multiply(p);
p.print();
system("pause");
pp.print();
return 0;
}
打印方法仅在乘法之前有效,在相乘之后它会无限地打印第一个元素 . 乘法方法应该是无效的,但我试图让它工作,所以我试图让它返回一个新的多项式对象 .