Лично я бы получил функцию производной, возвратившую Poly, а не изменив существующий. Что-то вроде этого
Poly derivative() {
Poly res;
Term *temp1 = this->term_t;
while (temp1 != NULL) {
int nexp = temp1->getExp() - 1;
int ncoef = temp1->getCoef() * temp1->getExp();
res.add(new Term(ncoef, nexp));
temp1 = temp1->getNext();
}
return res;
}
Что касается проблемы печати, хотя, да, вы не предоставили достаточно кода, чтобы действительно знать, что происходит. Итак, я написал свои собственные ... вот как я подхожу к проблеме. Первый класс Term как этот
class Term {
public:
Term(int coef, int exp) {
this->coef = coef;
this->exp = exp;
this->next = NULL;
}
std::string toString() const {
std::stringstream ss;
if (this->coef == 0) return "0";
if (this->exp == 0) ss << this->coef;
else {
if (this->coef != 1) ss << this->coef;
ss << "x";
if (this->exp != 1) ss << "^" << this->exp;
}
return ss.str();
}
int getCoef() const {return this->coef;}
int getExp() const {return this->exp;}
Term* getNext() const {return this->next;}
void setNext(Term* n) {this->next = n;}
private:
int coef;
int exp;
Term* next;
};
затем поли класс, как этот
class Poly {
public:
Poly() {
this->term_t = NULL;
}
void add(Term* nt) {
if (this->term_t == NULL) {
this->term_t = nt;
} else {
Term* t = this->term_t;
while(t->getNext() != NULL) t = t->getNext();
t->setNext(nt);
}
}
std::string toString() const {
std::stringstream ss;
Term* t = this->term_t;
while (t != NULL) {
ss << t->toString();
if (t->getNext() != NULL) ss << " + ";
t = t->getNext();
}
return ss.str();
}
Poly derivative() {
Poly res;
Term *temp1 = this->term_t;
while (temp1 != NULL){
int nexp = temp1->getExp() - 1;
int ncoef = temp1->getCoef() * temp1->getExp();
res.add(new Term(ncoef, nexp));
temp1 = temp1->getNext();
}
return res;
}
private :
Term* term_t;
};
Это было бы оставить управление памятью Срока объектов до пользователей класса, но вы также можете написать деструктор для класса Poly, который их удаляет.
Что ваш метод 'Poly :: производный()' имеет отношение к печати поли? Представленный вами фрагмент кода не имеет никакого отношения к вашему вопросу. – greatwolf