就個人而言,我會派生函數返回一個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;
}
至於雖然打印問題,是啊,你有沒有提供了足夠的代碼的真正瞭解發生了什麼事情。所以,我寫了自己的...這是我如何處理這個問題。首先這樣
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 :: derivative()方法與打印poly有什麼關係?你提出的代碼片段與你的問題沒有任何關係。 – greatwolf