重载+运算符以添加2个多项式 [英] overload the + operator to add 2 polynomials
问题描述
我试图添加存储在二维数组中的两个多项式,第一行存储系数,第二行存储度。
我创建了一个重载+函数,但在这里我使用2D分配的内存数组,当函数被调用时崩溃。
**更新:现在运行,但结果是一些大的负数。
复制构造函数和重载= operator
// overload +
多项式多项式::运算符+ )
{
maxExp = right.maxExp;
poly = new int * [maxExp];
for(int i = 0; i *(poly + i)= new int [2]
多项式temp = * this;
for(int i = 0; i {
for(int j = 0; j <2; j ++)
temp.poly [i] [j] = poly [i] [j] + right.poly [i] [j];
}
}
return temp;
}
最显着的是第一行:
delete [] poly;
销毁其中一个加号( x
在 x + y
)。
删除[]
。这不能解决这个问题,但会使情况变得更糟:你仍在覆盖被动语,但现在正在泄漏更多的记忆。 I'm trying to add two polynomials stored in a 2D array with the first rows store the coefficients and the second row store the degree.
I created a overloading + function but here I use 2D allocated memory array and it crashes when the function is called.
**Update: it runs now but the results are some big negative numbers
FYI, I have a copy constructor and an overloading = operator
// overload +
Polynomial Polynomial::operator+(const Polynomial &right)
{
maxExp = right.maxExp;
poly = new int *[maxExp];
for (int i=0; i < maxExp; i++)
*(poly + i) = new int[2];
Polynomial temp = *this;
for (int i=0; i < maxExp; i++)
{
for (int j=0; j < 2; j++)
{
temp.poly[i][j] = poly[i][j] + right.poly[i][j];
}
}
return temp;
}
There are multiple problems, but the most glaring one is that the very first line:
delete [] poly;
destroys one of the summands (the x
in x + y
). It also leaks memory, but at this point this is secondary.
edit: I notice that you've edited the delete[]
out of your question. This doesn't fix the problem, but makes it worse: you're still overwriting the summand, but now are leaking even more memory.
这篇关于重载+运算符以添加2个多项式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!