使用运算符重载的多项式运算

Vla*_*lad 3 c++ operations polynomial-math

我正在尝试使用运算符重载来定义我的多项式类的基本运算(+, - ,*,/)但是当我运行程序时它会崩溃并且我的计算机冻结.

UPDATE4

好.我成功完成了三次操作,剩下的唯一一次是划分.

这是我得到的:

polinom operator*(const polinom& P) const
{
    polinom Result;
    constIter i, j, lastItem = Result.poly.end();
    Iter it1, it2, first, last;
    int nr_matches;

    for (i = poly.begin() ; i != poly.end(); i++) {
         for (j = P.poly.begin(); j != P.poly.end(); j++)
              Result.insert(i->coef * j->coef, i->pow + j->pow);
    }

    Result.poly.sort(SortDescending());

    lastItem--;

    while (true) {
        nr_matches = 0;

        for (it1 = Result.poly.begin(); it1 != lastItem; it1++) {
             first = it1;
             last = it1;
             first++;
             for (it2 = first; it2 != Result.poly.end(); it2++) { 
                  if (it2->pow == it1->pow) {
                      it1->coef += it2->coef;
                      nr_matches++;
                  }
             }

             nr_matches++;
             do {
                last++;
                nr_matches--;
             } while (nr_matches != 0);

             Result.poly.erase(first, last);
        }   
        if (nr_matches == 0)
            break;
    }     

    return Result;
}
Run Code Online (Sandbox Code Playgroud)

Unc*_*ens 5

while (i != poly.end() || P.i != P.End())
Run Code Online (Sandbox Code Playgroud)

我认为你需要&&那里,否则只有当i和pi同时到达各自的终点时,循环终止.

否定的逻辑是棘手的.可能更容易将其视为:

while (!(i == poly.end() || j == P.End())) //while neither iterator has reached end
Run Code Online (Sandbox Code Playgroud)

根据布尔运算,它与:

while (!(i == poly.end()) && !(j == P.End()))
while (i != poly.end() && j != P.End())
Run Code Online (Sandbox Code Playgroud)

如果两者都相等,你似乎也没有递增迭代器(无限循环导致无限多的内存分配?).


样式问题:最好将迭代器用作局部变量.如果在开始在方法中使用它们之前它们应该被"初始化",则不要使变量类成员,并且在方法完成后它们变得无用.

也更喜欢通过const引用传递参数,如果它们不修改当前对象,则标记成员函数const(operator+不应该):

 polinom operator+(const polinom& P) const;
Run Code Online (Sandbox Code Playgroud)

(这将揭示制作本地使用的迭代器成员的问题 - 您将修改实例!)