0

我正在开发一个从函数类派生多项式类的程序。我几乎完成了,但我遇到了最后一个问题。

我正在调用“=”运算符。在 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;
    }

我愿意分享尽可能多的代码。感谢您的任何帮助!

4

2 回答 2

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 ) {...}
于 2012-11-30T05:55:08.757 回答
1

构造函数和复制构造函数都有问题。复制构造函数像普通构造函数一样从无到有构造对象(但随后它从其他对象复制相应的值),因此您不应该在那里检查值,只需创建它即可。不需要空白返回运算符。此外,您还存在 a 的 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;
}
于 2012-11-30T05:23:59.503 回答