如何解决使用数组 C++ 的析构函数崩溃程序
我正在学习 cpp 并且我一直试图正确分配内存,但现在在添加解构函数后,它崩溃了,HEAP CORRUPTION DETECTED。 我希望能够让 W1 小于 W2。现在,如果 W1 大于 W2,程序可以工作(没有析构函数 ofc),否则它会将结果削减到 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;
}
首先,我该如何修复析构函数? 感谢您抽出宝贵时间。
解决方法
你的析构函数没问题。 问题在于您的 plus 运算符。 您需要创建一个能够存储所有系数的数组并返回对象的副本。 目前你改变了你的第一个操作数。 还有其他问题,但它们不在这个问题范围内。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。