我做了一个名为cell
. 在这个类中有一个cell
指针数组。标题如下所示:
class cell
{
public:
cell();
cell *c[8];
void creatcells();
virtual ~cell();
..
}
该cpp
文件如下所示:
cell::cell()
{
//ctor
for(int i=0;i<8;i++)
{
c[i]=NULL;
}
}
void cell::creatcells()
{
cell c1,c2,c3,c4,c5,c6,c7,c8;
c[0]=&c1;
c[1]=&c2;
c[2]=&c3;
c[3]=&c4;
c[4]=&c5;
c[5]=&c6;
c[6]=&c7;
c[7]=&c8;
}
cell::~cell()
{
for(int i=0; i<8; i++)
{
if (c[i]!=NULL)
{
delete c[i];
}
}
delete[] c;
}
但是每次程序结束就崩溃,为什么呢?
我试过没有if (c[i]!=NULL)
,但这没有帮助。只有没有 for 循环,代码才能完美结束,但我知道这也必须删除。我想我正确地写了析构函数,不是吗?
void cell::creatcells()
{
cell c1,c2,c3,c4,c5,c6,c7,c8;
c[0]=&c1;
c[1]=&c2;
...
以上所有cell
对象在结束时自动销毁createcells()
。所以delete c[i];
在析构函数中是UB。你想要的是
c[0]= new cell();
c[1]= new cell();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句