overload *运算符乘以2个多项式

时间:2013-03-03 07:38:54

标签: c++ polynomial-math

我正在尝试使用重载*运算符

编写乘法2多项式

这是重载* func

Polynomial Polynomial::operator * (const Polynomial &right)
{
    Polynomial temp;
    temp.setPolynomial(right.maxExp + maxExp + 1);
    for (int i = 0; i < maxExp; i++)
    {
        for (int j = 0; j < right.maxExp; j++)
            temp.poly[1][i+j] += poly[0][i] * right.poly[0][j];
    }
    return temp;
}

数组结果,其中第一行是系数,第二行存储指数。

The first (original) polynomial is: (degree = 4, F = x^2)
0 0 1 0 0
0 0 2 0 0
The second polynomial is: (degree = 4, F = x^2)
0 0 1 0 0
0 0 2 0 0
The result polynomial is: // the location of the result is right (x^4)
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0 0

多项式类

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; // get the maxExp (highest exponent)
    int getCoefficient(int,int) const; // get a specific exponential value

    // overloading operators
    void operator=(const Polynomial &); // assignment
    Polynomial operator+(const Polynomial &); // addition
    Polynomial operator-(const Polynomial &); // substraction
    Polynomial operator*(const Polynomial &);
}

问题:我的代码产生了什么错误?谢谢!

1 个答案:

答案 0 :(得分:1)

有了这个,你用多个系数更新结果指数;

 temp.poly[1][i+j] += poly[0][i] * right.poly[0][j];

我认为代码应该是

for (int j = 0; j < right.maxExp; j++)
{
    temp.poly[0][i+j] += poly[0][i] * right.poly[0][j];
    if (temp.poly[0][i+j] != 0)
        temp.poly[1][i+j] = i+j;
}

此外,我认为在您的代码中存储指数是冗余信息,因为数组中的位置本身反映了指数