#ifndef __MEM__H
#define __MEM__H
#include<iostream>
using namespace std;
//自动管理内存块
typedef unsigned char byte;
class Mem
{
private:
byte* mem;
int size;
void ensureMinSize(int minSize);
public:
Mem();
Mem(int sz);
~Mem();
int msize();
//byte* pointer();
byte* pointer(int minSize=0);
};
Mem::Mem()
{
mem =0;
size =0;
}
Mem::Mem(int sz)
{
mem =0;
size =0;
ensureMinSize(sz);
}
Mem::~Mem()
{
delete []mem;
}
int Mem::msize()
{//当前的内存大小
return size;
}
void Mem::ensureMinSize(int minSize)
{//自动增长申请内存
if(size < minSize)
{
byte* newmem = new byte[minSize];
memset(newmem+size,0,minSize - size);
memcpy(newmem,mem,size);
delete []mem;
mem = newmem;
size = minSize;
}
}
//byte* Mem::pointer()
//{//返回当前内存的首地址
//return mem;
//}
byte* Mem::pointer(int minSize)
{//重新增长内存并返回内存的起始地址
ensureMinSize(minSize);
return mem;
}
#endif
#include "mem.h"
class Mystring
{
public:
Mystring();
Mystring(char *str);
~Mystring();
void concat(char *str);
void print(ostream &os);
private:
Mem *buf;
};
Mystring::Mystring()
{
buf = 0;
}
Mystring::Mystring(char *str)
{
buf = new Mem(strlen(str)+1);
strcpy((char*)buf->pointer(),str);
}
void Mystring::concat(char *str)
{
if(!buf)
buf = new Mem;
strcat((char*)buf->pointer(buf->msize()+strlen(str)),str);
}
void Mystring::print(ostream &os)
{
if(!buf)
return ;
os<<buf->pointer()<<endl;
}
Mystring::~Mystring()
{
delete buf;
}
void main()
{
Mystring s("mytest");
s.print(cout);
s.concat(" is weikai");
s.print(cout);
}
尽量不要把默认参数作为一个标志去决定执行函数哪一块,这是基本原则.在这种情况下,只要能够就应该把函数分解成两个或者多个重载的函数。下面这种方式就是把默认参数作为决定执行
Mystring::Mystring(char *str)
{
if(! *str)
{
buf =0;
return;
}
buf = new Mem(strlen(str)+1);
strcpy((char*)buf->point(),str);
}