在GCCAVR C++中如何重载new

2009年04月02日 23:05    发布者:hotpower
hotpower 发表于 2005-1-31 00:24
在GCCAVR C++中如何重载new,delete

void * operator new (size_t size)
{
void * ptr;
  ptr = malloc(size);
  if (!ptr) return ptr;
  memset(ptr, '\0', size);
  return ptr;
}


void  operator delete(void * obj)
{
  free(obj);
}

应用:
inline String::String(const char * str)
{
  if (!str) {
    _size = 0;
    _string = 0;
  }
  else {
    _size = strlen(str);
    _string = new char(_size + 1);
    strcpy(_string, str);
  }
}

inline String & String::operator = (const char * s)
{
  if (!s) {
    _size = 0;
    delete _string;
    _string = 0;
  }
  else {
    _size = strlen(s);
    delete _string;
    if (_size == 0) _string = 0;
    else {
      _string = new char(_size + 1);
      strcpy(_string, s);
    }
  }
  return *this;
}

网友评论

hotpower 2009年04月02日
可恨的:)
hotpower 2009年04月03日
2个“:”后跟o就坏事了
admin 2009年04月04日
::O
admin 2009年04月04日
::O
hotpower 2009年04月04日
C++中运算符重载operator是不允许大写O的~~~

俺的程序都是源码,不可能误导人民群众。
所以本站很不顺也~~~
李冬发 2009年04月06日
呵呵
老郭 2009年04月06日
这也太幽默了~
李冬发 2009年04月24日
经常有这个问题。

::o
李冬发 2009年04月24日
用代码就不会了
李冬发 2009年04月24日
这样就好了。在GCCAVR C++中如何重载new,delete

void * operator new (size_t size)
{
void * ptr;
  ptr = malloc(size);
  if (!ptr) return ptr;
  memset(ptr, '\0', size);
  return ptr;
}


void  operator delete(void * obj)
{
  free(obj);
}

应用:
inline String::String(const char * str)
{
  if (!str) {
    _size = 0;
    _string = 0;
  }
  else {
    _size = strlen(str);
    _string = new char(_size + 1);
    strcpy(_string, str);
  }
}

inline String & String::operator = (const char * s)
{
  if (!s) {
    _size = 0;
    delete _string;
    _string = 0;
  }
  else {
    _size = strlen(s);
    delete _string;
    if (_size == 0) _string = 0;
    else {
      _string = new char(_size + 1);
      strcpy(_string, s);
    }
  }
  return *this;
}
bakedham 2009年04月25日
恩。真有办法
hotpower 2009年06月10日
搞不清楚~~~
pcbkey 2015年02月07日
支持一下