我正在开发一个从函数类派生多项式类的程序。我几乎完成了,但我遇到了最后一个问题。
我正在调用“=”运算符。在 main 函数中,它看起来像这样:
f3 = f2 * 2;
f3 和 f2 都是多项式数据类型。乘法运算符也被重载,并且已经过测试可以工作。当我的程序达到这一点时,它会崩溃。这是崩溃的回溯:
Program received signal SIGABRT, Aborted.
0x00000000 in ?? ()
(gdb) bt
#0 0x00000000 in ?? ()
#1 0x77cbf8c1 in ntdll!RtlUpdateClonedSRWLock ()
from /cygdrive/c/Windows/system32/ntdll.dll
#2 0x75ab0816 in WaitForSingleObjectEx ()
from /cygdrive/c/Windows/syswow64/KERNELBASE.dll
#3 0x000000ec in ?? ()
#4 0x00000000 in ?? ()
不幸的是,这并没有给我任何提示。
最后,这里是重载的 operator=:
Polynomial& Polynomial::operator=(const Polynomial& rhs) {
if(this->a)
delete [] this->a;
this->setName(rhs.getName());
this->degree = rhs.degree;
a = new double[this->degree];
for(int i = 0; i < this->degree; i++)
{
this->a[i] = rhs.a[i];
}
return *this;
}
以及类的头文件。
class Polynomial : public Function
{
public:
Polynomial (const string& name = "unnamed");
Polynomial (const Polynomial& rhs);
void setCoefficients (int degree, ...);
int getDegree() const { return degree; }
double operator[] (int i) const;
double operator() (double x) const;
Polynomial operator* (double c) const;
Polynomial& operator*= (double c);
Polynomial& operator=(const Polynomial& rhs);
void write(ostream& outfile) const;
private:
double* a;
int degree;
};
Polynomial operator* (double c, const Polynomial& p);
构造函数:
(Polynomial::Polynomial (const string& name) {
a = new double[1];
a[0] = 0;
degree = 0;
return;
}
Polynomial::Polynomial (const Polynomial& rhs) {
//Null a, and then pass over to the overloaded = operator.
if(this->a)
delete [] this->a;
*this = rhs;
return;
}
我愿意分享尽可能多的代码。感谢您的任何帮助!