我正在构建一个与链表一起使用的程序,以便存储多项式。基本上,用户输入.txt文件的名称,该文件被打开,读取,并且系数和指数被插入到每个节点的数据字段中。节点表示多项式中的项。我有两个类,外部类是Polynomial,嵌套类是Term。我已经开始编写定义来重载加法运算符。到目前为止,关于如何执行此操作的基本思路是将for循环嵌套在另一个for循环中。我只是不知道如何将我的结果存储在我创建的新Polynomial对象中......
#include "polynomial.h"
#include <sstream>
#include <cmath>
double Polynomial::TOL = .000000000001; // tolerance for floating pt. equality
Polynomial::Term::Term( double c, int e, shared_ptr<Term> n )
{
coeff = c; exponent = e; next = n;
}
Polynomial::Polynomial()
{
head = nullptr;
}
Polynomial::Polynomial( string & str )
{
stringstream ss( str ); // stringstream lets us extract items separated by
// whitespace simply by using the >> operator
double coefficient; // to hold the coefficient
int exp; // to hold the exponent
head = nullptr; // initialize head to null
// read in coefficient-exponent pairs and add each term to the list
// ----------------------------------------------------------------
while (ss >> coefficient >> exp)
if (coefficient != 0) // don't make a 0 term
head = shared_ptr<Term>(new Term( coefficient, exp, head ));
}
到目前为止,重载了添加功能
Polynomial Polynomial::operator+( const Polynomial &other ) const
{
shared_ptr<Polynomial> result = shared_ptr<Polynomial>(new Polynomial()); // where you are going to store your results
shared_ptr<Polynomial::Term> a = this->head;
shared_ptr<Polynomial::Term> b = other.head;
while(a != nullptr && b != nullptr)
{
for(a; a != nullptr; a->next)
{
for(b; b!=nullptr; b->next)
{
if(a->exponent == b->exponent)
{
sum = a->coeff+b->coeff;
result = shared_ptr<Term> newTerm (new Term( sum, exp, head ));
}
}
return newTerm;
}
}