如何修复基类中的内存分配错误

How to fix a memory allocation error in a base class?

本文关键字:内存 分配 错误 何修复 基类      更新时间:2023-10-16

我编写了一个包含两个类的程序。基类包括其派生类的指针对象。然后在基类的构造函数中初始化指针对象。

My Compiler在编译过程中没有给我错误,但是当控制台窗口出现时,程序崩溃,为派生类的对象给出UNHANDLED EXCEPION BAD ALLOCATION的错误。我该怎么做才能修好它?

代码如下:

class x;
class y
{
    private:
      x *objx; // here is the error
    ...........................
};
class x: public y
{
    ...........................
    ................
};
y::y()
{
     objx=new x(); // bad allocation and the program crashes
     // I have also tried this way by commenting objx=new x();
     *objx=0; // but still the program crashes.
}

由于调用派生类中的构造函数将调用父类中的构造函数,因此看起来您将在那里遇到递归构造问题-这可能是导致异常的原因。

为了避免这种情况,您可以将"new x()"从构造函数中移到它自己的函数中。

正如在另一个答案中解释的那样,您有一个无限递归构造问题。您可以尝试在构造函数中将指针设置为空,并创建一个方法init,该方法将生成实际的对象:

y::y()
{
     // *objx=0; // this is wrong, you don't want to dereference your pointer.
     objx = 0;   // this should work
}
void y::init()
{
     objx = new x();
}