我的作业一直有问题,关于制作多项式类和重载一些运算符以根据类工作。我已经完成了大部分工作,但我的析构函数或函数似乎有问题。
问题是,根据我的调试(如果我做对了,我认为我做到了),当与我的复制构造函数一起使用时,我的 + 运算符函数 get 的返回值被破坏了两次,如下所示:
//polynomials p1 and p2 are declared and given values beforehand
Polynomial p5=Polynomial();
p5=p1+p2;
这会导致堆损坏错误。
这是我的标题代码:
#ifndef POLYNOMIAL_H_
#define POLYNOMIAL_H_
#include <iostream>
using namespace std;
class Polynomial
{
public:
Polynomial();
Polynomial(int);
~Polynomial();
Polynomial(const Polynomial &);
int getOrder() const;
double getCoefficient(int) const;
void setOrder(int);
void setCoefficient(int,double);
const Polynomial &operator=(const Polynomial &);
const bool &operator==(const Polynomial &);
const double &operator()(double &);
const bool &operator!=(const Polynomial &);
friend Polynomial operator+(const Polynomial &poly1, const Polynomial &poly2);
friend Polynomial &operator+=(Polynomial &poly1,const Polynomial &poly2);
friend Polynomial operator-(const Polynomial &poly1, const Polynomial &poly2);
friend Polynomial &operator-=( Polynomial &poly1,const Polynomial &poly2);
friend Polynomial operator*(Polynomial poly1,double num);
private:
int order;
double *coefficient;
};
#endif
这是我的重载 + 函数,它不漂亮,但我的问题不是计算,而是内存。我在课堂上将它声明为友元函数,根据我的作业规则,我需要在 main.cpp 文件中将它作为自由函数而不是成员函数来实现。
Polynomial operator+(const Polynomial &poly1, const Polynomial &poly2) //the overloaded +operator. makes the order of the result the bigger order and adds the coefficients for all the orders. returns the result.
{
Polynomial result;
if(poly1.order >= poly2.order)
{
result.setOrder(poly1.order);
for(int i=poly1.order;i>poly2.order;i--)
{
result.setCoefficient(poly1.order-i, poly1.coefficient[poly1.order-i]);
}
for (int i =poly2.getOrder(); i>=0;i--)
{
result.setCoefficient(poly1.order-i,poly1.coefficient[poly1.order-i]+poly2.coefficient[poly2.order-i]);
}
}
else
{
result.setOrder(poly2.order);
for(int i=poly2.order;i>poly1.order;i--)
{
result.setCoefficient(poly2.order-i, poly2.coefficient[poly2.order-i]);
}
for (int i =poly1.order; i>=0;i--)
{
result.setCoefficient(poly2.order-i,poly1.coefficient[poly1.order-i]+poly2.coefficient[poly2.order-i]);
}
}
return result;
}
我们还需要重载 = 运算符,如果需要,这就是该函数。
const Polynomial &Polynomial::operator=(const Polynomial &poly)
{
if(this!=&poly)
{
if(order==poly.order)
{
for(int i=0;i<=order;i++)
{
coefficient[i]=poly.coefficient[i];
}
}
else
{
coefficient=new double[poly.order];
order=poly.order;
for(int i=0;i<=order;i++)
{
coefficient[i]=poly.coefficient[i];
}
}
}
return *this;
}
请记住,我真的是编码和 C++ 的初学者,感谢您提供的任何帮助。
编辑:添加深拷贝构造函数。
Polynomial::Polynomial(const Polynomial ©) //deep copy constructor
{
order=copy.order;
coefficient=new double[copy.order];
for (int i=0;i<=order;i++)
{
coefficient[i]=copy.coefficient[i];
}
}