哪位高手进来指点一下?我的类重载new和delete有问题

yangyanglei 2009-04-02 10:24:13
#include <iostream>
#include <cstring>
#include <cstddef>
#include <new>
const int maxnames=5;
class Names
{
char name[25];
static char Names::pool[];
static bool Names::inuse[maxnames];
public:
Names (char* s)
{ strncpy(name,s,sizeof(name));}
void* operator new(size_t) throw (bad_alloc);
void operator delete(void*)throw();
void display()
{std::cout<<name<<std::endl;}
};
char Names::pool[maxnames*sizeof(Names)];
bool Names::inuse[maxnames];
void* Names::operator new(size_t) throw(bad_alloc)
{
for(int p=0;p<maxnames;p++)
if(!inuse[p])
{
inuse[p]=true;
return pool+p*sizeof(Names);
}
throw bad_alloc();
}
void Names::operator delete(void* p) throw()
{
if(0!=p)
inuse[((char*)p-pool)/sizeof(Names)]=false;
}
int main()
{
Names* nm[maxnames];
int i;
for(i=0;i<maxnames;i++)
{
std::cout<<std::endl<<"Enter name # "<<i+1<<":";
char name[25];
std::cin>>name;
nm[i]=new Names(name);
}
for(i=0;i<maxnames;i++)
{
nm[i]->display();
delete nm[i];
}
return 0;
}
...全文
95 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
mengde007 2009-04-02
  • 打赏
  • 举报
回复
楼主,结贴给分吧,我可忙了一段时间,呵呵
mengde007 2009-04-02
  • 打赏
  • 举报
回复

#include <iostream>
#include <cstring>
#include <cstddef>
//#include <new>//既然你要重载,为什么还包含呢,去掉
const int maxnames=5;
class Names
{
char name[25];
static char Names::pool[];
static bool Names::inuse[maxnames];
public:
Names (char* s)
{ strncpy(name,s,sizeof(name));}
void* operator new(size_t) throw (std::bad_alloc);//标准的
void operator delete(void*)throw();
void display()
{std::cout <<name <<std::endl;}
};
char Names::pool[maxnames*sizeof(Names)];
bool Names::inuse[maxnames];
void* Names::operator new(size_t) throw(std::bad_alloc)
{
try
{
for(int p=0;p <maxnames;p++)
if(!inuse[p])
{
inuse[p]=true;
return pool+p*sizeof(Names);
}
}
catch(std::bad_alloc & ba)
{
std::cout<<ba.what()<<std::endl;
}
return NULL;
}
void Names::operator delete(void* p) throw(std::bad_alloc)
{
if(0!=p)
inuse[((char*)p-pool)/sizeof(Names)]=0;
}
int main()
{
Names* nm[maxnames];
int i;
for(i=0;i <maxnames;i++)
{
std::cout <<std::endl <<"Enter name # " <<i+1 <<":";
char name[25];
std::cin>>name;
nm[i]=new Names(name);
}
for(i=0;i <maxnames;i++)
{
nm[i]->display();
delete nm[i];
}
return 0;
}

//以上程序经过测试,完全通过,楼主可验证
lgccaa 2009-04-02
  • 打赏
  • 举报
回复
有什么问题啊?描述下
问问题要明确一点,还有就是说明白一点,答问题的可以比较快知道问题的所在和楼主不明白的地方,这样对楼主也比较有益的,经过思考的问题解决了会比较深刻的

64,648

社区成员

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

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