gpt4 book ai didi

c++ - 如何修复基类中的内存分配错误?

转载 作者:行者123 更新时间:2023-11-28 03:44:12 26 4
gpt4 key购买 nike

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

我的编译器在编译过程中没有给我报错,但是当控制台窗口出现时程序崩溃,为派生类的对象报错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()”移到它自己的函数中。

关于c++ - 如何修复基类中的内存分配错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8125215/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com