【发布时间】:2021-07-16 07:16:06
【问题描述】:
我正在学习 cpp,我尝试始终正确分配内存,但现在在添加解构函数后,它会因 HEAP CORRUPTION DETECTED 而崩溃。 我希望能够使 W1 小于 W2。现在,如果 W1 大于 W2,程序可以工作(没有 c 的析构函数),否则它将结果削减到 W1 的大小。 我使用 Visual Studio 2019。 这是我的代码:
#include <iostream>
using namespace std;
class Polynomial
{
private:
int degree_;
int* ptr= nullptr;
public:
Polynomial()
{
int* ptr = new int[1];
ptr[0] = 0;
}
Polynomial(int degree)
{
degree_ = degree;
ptr = new int[degree_ + 1]; //+1 for the coefficient next to x^0
}
Polynomial(const Polynomial& oldobj)
{
degree_ = oldobj.degree_;
ptr = new int[degree_ + 1];
*this = oldobj;
//for (int i = 0; i < degree + 1; i++)
//ptr[i] = oldobj.ptr[i];
}
~Polynomial()
{
delete[]ptr;
}
Polynomial& operator+(const Polynomial& tempobj)
{
for (int i = 0; i <= tempobj.degree_; i++)
{
ptr[i] += tempobj.ptr[i];
}
return *this;
}
Polynomial& operator=(const Polynomial& tempobj)
{
degree_ = tempobj.degree_;
ptr = tempobj.ptr;
return *this;
}
friend istream& operator>>(istream& in, Polynomial& obj);
friend ostream& operator<<(ostream& oou, const Polynomial& obj);
};
istream& operator>>(istream& in, Polynomial& obj)
{
for (int i = obj.degree_; i >= 0; i--)
{
if (i == 0)
{
cout << "Last Coefficient: ";
cin >> obj.ptr[i];
break;
}
cout << "Coefficient in x^" << i << ": ";
cin >> obj.ptr[i];
}
return in;
}
ostream& operator<<(ostream& out, const Polynomial& obj)
{
cout << "f(x)= ";
for (int i = obj.degree_; i >= 0; i--)
{
cout << obj.ptr[i] << "x^" << i << " ";
}
return out;
}
int main()
{
Polynomial W1(2), W2(4), W3; //I want W1 to be able to swap places with W2.
//Right now it works only when W2 is smaller than W1;
cin >> W1;
cout << endl << W1<<endl;
cin >> W2;
cout << endl << W2 << endl;
W3 = W1 + W2;
cout << endl << W3;
return 0;
}
首先,我该如何修复析构函数? 感谢您的宝贵时间。
【问题讨论】:
-
检查您的
operator+逻辑。如果tempobj的度数大于this对象的度数会怎样? -
更糟糕的是,当 default 构造函数被实际使用时,成员
degree_的值是多少?您的赋值运算符是 (a) 泄漏内存和 (b) 对现在共享的指针进行双重删除的秘诀。 -
您的 operator= 也有问题,因为您将相同的指针分配给两个不同的多项式。当第一个析构函数被调用时一切都会好起来,但是当第二个析构函数被调用时,多项式将尝试释放一部分已经被释放的内存,因此你的堆损坏。
-
@TheUndeadFish 哦,这是编辑后的代码,我在其中删除了 operator+ 中的 if/else 部分,看看它是否有帮助。这就是它的样子: if(degree_ tempobj.degree_)
-
你最好只使用矢量。
标签: c++ destructor heap-memory polynomials