不能适当地使操作员“新"操作超载.和“删除"? [英] not able to properly overload operator "new" and "delete"?

查看:89
本文介绍了不能适当地使操作员“新"操作超载.和“删除"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



提前非常感谢.
我正在DevC ++环境中从事C ++项目.

我正在尝试重载"new"和"delete"运算符,但无法调用这些重载的运算符.您能帮我确定我在哪里做错吗?

Hi,

Thanks very much in advance.
I am working on C++ project in DevC++ environment.

I am trying to overload "new" and "delete" operators but I am unable to call those overloaded operators. Can you please help me identifying where am I making mistake??

void* operator new (size_t , int )// working
{
      cout<<"This is overloaded-new operator"<<endl;
}

void operator delete (void* pointer, int iData)// working
{
     cout<<"This is overloaded-delete operator"<<endl;
}


void main()
{
// as per my understanding following should call overloaded operators
// following gives error: invalid conversion from int to void*
//          initializing argument 2 of void* operator new[](size_t, void*)
void* chObjNew = new(10)char[10];
// following error: type int argument given to delete expected pointer
     delete(chObjNew, 10) ;
}

推荐答案

我认为您在分配数组时必须超载new的数组形式

I think you have to overload the array form of new as you are allocating for array

void* operator new[](size_t t) 
{
     // ...
}



并类似地删除



and similarly delete

void operator delete[](void* ptr
{
   // .....
}


请在:
上找到包含整齐实例的出色解释.
http://bytes.com/topic/c/answers/129162-overloading-new- delete-operators [^ ]
Do find excellent explanation with neat exaples at :

http://bytes.com/topic/c/answers/129162-overloading-new-delete-operators[^]


如果您完全有资格删除,它将起作用:我认为:
If you fully qualify your delete it''ll work I think:
::operator delete(chObjNew, 10);



希望这会有所帮助,
弗雷德里克(Fredrik)



Hope this helps,
Fredrik


这篇关于不能适当地使操作员“新"操作超载.和“删除"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆