诡异! 非高手或喜欢答非所问的人勿进。

zg351229063 2007-09-19 05:58:34
我现在有一个子类和一个父类,还有一个存有子类指针的数组。现在,我要执行下面的操作:
1. 回收字类指针数组中指针对应的内存。(用delete回收)
2. 为了代码的优美,我将父类的析构函数声明为虚函数。

但是,我回收内存的程序崩溃了。奇怪的是,如果父类的析构函数不是虚函数的话,就没有崩溃的问题。

请问,这是为什么?
请高手指教!
...全文
293 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
yiqisetian 2007-09-22
  • 打赏
  • 举报
回复
这种标题,有辱斯文,我就答非所问了,
ddc 2007-09-21
  • 打赏
  • 举报
回复
如果你的指针数组声明是子类的,指向的对象也是子类而不是强转的,那么这个错误和父类没有任何关系。
czg516 2007-09-21
  • 打赏
  • 举报
回复

不管程序是否优美,只要是父类必须声明成虚拟的破坏函数。详细请看effect C++


帖出代码让大家看下!~~
tangshuiling 2007-09-21
  • 打赏
  • 举报
回复
如ls所说,照楼主的描述怎么可能会有问题。帖代码看看吧
cnvb 2007-09-20
  • 打赏
  • 举报
回复
照楼上的写法好像没有出错...
iambic 2007-09-20
  • 打赏
  • 举报
回复
从你说的看不出来有什么问题。请贴完整代码。如果代码比较长请删减。
独孤过儿 2007-09-20
  • 打赏
  • 举报
回复
#include <iostream>
using namespace std;

class base{
public:
base()
{
cout<<"base::base()"<<endl;
}
virtual ~base()
{
cout<<"~base::base()"<<endl;
}
};

class inher: public base{
public:
inher()
{
cout<<"inher::inher()"<<endl;
cout<<"Begin New memory!"<<endl;
ptr = new char[100];

if ( !ptr )
{
cout<<"New memory failed!"<<endl;
}
else
{
cout<<"New memory successful!"<<endl;
}

}
~inher()
{
cout<<"~inher::inher()"<<endl;
cout<<"Begin Delete memory!"<<endl;
delete [] ptr;
cout<<"Delete memory successful!"<<endl;
}
private:
char* ptr;
};

int main()
{
inher* pInher[2];
pInher[0] = new inher;
pInher[1] = new inher;

delete pInher[0];
delete pInher[1];

return 0;
}
zg351229063 2007-09-20
  • 打赏
  • 举报
回复
我实际上用的是一个动态数组,所以,不能用delete []arr而且,我经常要对单个数据进行操作,所以不能用delete []arr的形式。
wayne1986 2007-09-20
  • 打赏
  • 举报
回复
我想你还是用delete []arr;比较好
zg351229063 2007-09-20
  • 打赏
  • 举报
回复
不好意思,我也不想用这个题目,感觉不太礼貌。可是,也没办法,时间长了,我想你会明白的感受的,呵呵。

我出现的问题基本上和你写的差不多,区别在于你没有给出一个派生类的指针数组。
应该是下面这样:
inher* arr[2];
arr[0] = new inher;
arr[1] = new inher;

我回收的时候是这样的。
delete arr[0];
delete arr[1];
独孤过儿 2007-09-19
  • 打赏
  • 举报
回复
PS:下次别用这样的标题了啊,虽然我回答你的问题了,可我不是高手,而且我也不知道我的回

答是否是答非所问,我只是按我的理解给你最完美的答案。
独孤过儿 2007-09-19
  • 打赏
  • 举报
回复
写了个测试代码,看看是不是要这种效果:

#include <iostream>
using namespace std;

class base{
public:
base()
{
cout<<"base::base()"<<endl;
}
virtual ~base()
{
cout<<"~base::base()"<<endl;
}
};

class inher: public base{
public:
inher()
{
cout<<"inher::inher()"<<endl;
cout<<"Begin New memory!"<<endl;
ptr = new char[100];

if ( !ptr )
{
cout<<"New memory failed!"<<endl;
}
else
{
cout<<"New memory successful!"<<endl;
}

}
~inher()
{
cout<<"~inher::inher()"<<endl;
cout<<"Begin Delete memory!"<<endl;
delete [] ptr;
cout<<"Delete memory successful!"<<endl;
}
private:
char* ptr;
};

int main()
{
inher* pInher;
pInher = new inher[2];

delete [] pInher;

return 0;
}

64,646

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧