纯自己想,想到用指针的方式访问计数器,计数器与数据域同时间段开辟出来,放在头部,是个int类型。之后会写一个科学一点的,这个里面采用了强转这种不安全的方法。
#include
#include<string.h>
#include
#include<vld.h>
class String
{
public:
String()
{
pcount = NULL;
mptr = NULL;
}
String(const char * ptr)
{
mptr = new char[strlen(ptr)+5]();
pcount = (int *)mptr;
memset(pcount,0,4);
mptr = mptr + 4;
strcpy_s(mptr,strlen(ptr)+1,ptr);
(*pcount)++;
}
String(const String& rhs)//浅拷贝
{
mptr = rhs.mptr;
pcount = rhs.pcount;
(*pcount)++;
}
String& operator = (const String& rhs)//浅拷贝
{
if(this == &rhs)
{
return *this;
}
if((*pcount) == 1)
{
delete pcount;
}
--(*pcount);
mptr = new char[strlen(rhs.mptr)+5]();
pcount = (int *)mptr;
memset(pcount,0,4);
mptr = mptr + 4;
strcpy_s(mptr,strlen(rhs.mptr)+1,rhs.mptr);
(*pcount)++;
return *this;
}
char & operator [] (int index)//深拷贝
{
--(*pcount);
char * ptmp = mptr;
mptr = new char[strlen(ptmp)+5]();
pcount = (int *)mptr;
memset(pcount,0,4);
mptr = mptr + 4;
strcpy_s(mptr,strlen(ptmp)+1,ptmp);
(*pcount)++;
return mptr[index];
}
~String()//特殊处理
{
if((*pcount) == 1)
{
delete pcount;
}
(*pcount)--;
pcount = NULL;
mptr = NULL;
}
private:
int * pcount;
char * mptr;
};
int main()
{
String str1(“hello”);
String str2 = str1;
String str3(str1);
char p = str1[0];
return 0;
}