我正在從一個函數類派生Polynomial類的程序。我差不多完成了,但我遇到了最後一個問題。處理重載運算符時多項式類崩潰=
我在調用「=」運算符。在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;
}
我願意爲需要共享大量代碼。感謝您的任何幫助!
除其他事項外,你可能要檢查'這個==&rhs'在'運營商='否則,你可以這樣做'OBJ = obj'這將導致段錯誤。 –
我明白檢查以確保它是相同的對象,但我可以保證不會發生.. – mr0il
爲什麼你不使用'std :: vector',它會照顧整個內存管理業務? –