处理重载operator =时,多项式类崩溃

时间:2012-11-30 05:00:44

标签: c++

我正在开发一个从Function类派生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;
    }

我愿意分享尽可能多的代码。谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

构造函数和复制构造函数都存在问题。复制构造函数从正常构造函数构建对象(但随后它从其他对象复制相应的值),因此您不应该在那里检查值,只需创建它。空白返回运算符不需要。你也有一个问题,0和1的大小不一致。这段代码会更常见:

Polynomial::Polynomial (const string& name) : Function(name) {
    a = 0;
    degree = 0;
}

Polynomial::Polynomial (const Polynomial& rhs) {

    setName(rhs.getName());
    degree = rhs.degree;
    if(degree)
    {
        a = new double[degree];
        for(int i = 0; i < degree; i++)
            a[i] = rhs.a[i];
    }
    else
        a = 0;
}

const Polynomial& Polynomial::operator=(const Polynomial& rhs) {
    if(this != &rhs)
    {
        if(a)
            delete [] a;
        setName(rhs.getName());
        degree = rhs.degree;
        a = new double[degree];
        for(int i = 0; i < degree; i++)
            a[i] = rhs.a[i];
    }
    return *this;
}

答案 1 :(得分:1)

我认为问题出在你的拷贝构造函数中,在你的拷贝构造函数中:

//Null a, and then pass over to the overloaded = operator.
if(this->a)
    delete [] this->a;

a未在此处初始化,因此您无法将其删除,因此请将其替换为:

Polynomial::Polynomial(Polynomial const& other) : a( NULL ) {...}