其他分享
首页 > 其他分享> > c-覆盖删除运算符

c-覆盖删除运算符

作者:互联网

我想在班上重写delete运算符.这是我想做的,但没有成功.

class Complex{              
    void *operator new(size_t s);
    void operator delete(void *ptr);
};

void Complex::operator delete(void *ptr){
    delete ptr;
}

我得到错误:

deleting void* is undefined

解决方法:

如错误消息所示,您不能删除void *.尝试这个:

// See http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=40

#include <new> // for size_t

class Complex
{
public:
 Complex() {}
 ~Complex() {}
 static void* operator new (size_t size) {
  return new char[size];
 }
 static void operator delete (void *p) {
  return delete[] static_cast<char*>(p);
 }
};

int main () {
  Complex *p = new Complex;
  delete p;
}

标签:c,oop,new-operator
来源: https://codeday.me/bug/20191010/1888361.html