重载+运算符将两个多项式相加

overload + operator to add 2 polynomials C++

本文关键字:两个 多项式 运算符 重载      更新时间:2023-10-16

我正在编写将2个多项式相加的函数,其中2个多项式具有相同数量的最高次(所有项都不需要输入)的情况下工作良好,但是两个多项式具有不同程度的情况不工作,该函数以某种方式存储一些大值作为系数

这是函数

// overload +
Polynomial Polynomial::operator+(const Polynomial &right)
{
    // get the highest exponent value for result
    int highestExp = 0;
    if (maxExp < right.maxExp)
        highestExp = right.maxExp;
    else if (maxExp >= right.maxExp)
        highestExp = maxExp;
    Polynomial res;
    res.setPolynomial(highestExp);
    for (int coeff=0; coeff < highestExp; coeff++)
            res.poly[0][coeff] = poly[0][coeff] + right.poly[0][coeff];
    return res;
}
例如,

案例1:最高exp值相等

The first (original) polynomial is:
 - 4x^0 + x^1 + 4x^3 - 3x^4
The second polynomial is:
 - x^0 - x^3
The result polynomial is:
 - 5x^0 + x^1 + 3x^3 - 3x^4

case2:最高指数不等于

The first (original) polynomial is:
 - 4x^0 + x^1 + 4x^3 - 3x^4 (highest exp = 4)
The second polynomial is:
 - x^0 - x^3 (highest exp = 5)
The result polynomial is:
 - 5x^0 + x^1 + 3x^3 - 3x^4 - 33686019x^5 (highest exp = 5)

请帮忙!

更新:多项式类
class Polynomial
{
private:
    int **poly;
    int maxExp;
    void createPolynomialArray(int);
public:
    Polynomial();
    Polynomial(int); // constructor
    Polynomial(const Polynomial &); // copy constructor
    ~Polynomial(); // destructor
    // setter
    void setCoefficient(int,int);
    void setPolynomial(int);
    // getters
    int getTerm() const; 
    int getCoefficient(int,int) const; 
    // overloading operators
    void operator=(const Polynomial &); // assignment
    Polynomial operator+(const Polynomial &); // addition    
}

我想你要

Polynomial Polynomial::operator+(const Polynomial &right)
{
    Polynomial res;
    if(maxExp < right.maxExp)
    {
        res.setPolynomial(right.maxExp);
        int coeff = 0;
        for (; coeff < maxExp; coeff++)
                res.poly[0][coeff] = poly[0][coeff] + right.poly[0][coeff];
        for (; coeff < right.maxExp; coeff++)
                res.poly[0][coeff] = right.poly[0][coeff];
    }
    else
    {
        res.setPolynomial(maxExp);
        int coeff = 0;
        for (; coeff < right.maxExp; coeff++)
                res.poly[0][coeff] = poly[0][coeff] + right.poly[0][coeff];
        for (; coeff < maxExp; coeff++)
                res.poly[0][coeff] = poly[0][coeff];
    }
    return res;
}

您正在阅读超过较短多项式的末尾。

您似乎缺少对数组访问的边界检查。您看到奇怪值的原因是,在这种情况下,程序可能正在从未初始化的内存中读取垃圾值。但这是未定义行为,所以任何事情都有可能发生。像这样的错误最糟糕的部分是它们通常看起来工作得很好。

另外,我建议使用std::vector来存储系数,而不是原始指针。这样更容易使用,也更不容易出错。

注:另一个小问题是,我建议在if和for语句块周围使用大括号。它使所包含的代码更加清晰,并降低了在不更新大括号的情况下意外添加额外行的风险。或者,但愿不会有人使用多行宏。但这是个人喜好的问题。