stringクラス、浅いコピー、深いコピー(簡潔版)、書き込み時コピー
3151 ワード
#include
#include
#include
using namespace std;
class String
{
public:
String(const char*pStr="")
{
_pStr=new char[strlen(pStr)+1];
strcpy(_pStr,pStr);
}
String(const String& s)
:_pStr(s._pStr)
{}
String& operator=(const String& s)
{
if(this!=&s)
{
_pStr=s._pStr;
}
return *this;
}
~String()
{
}
private:
char* _pStr;
};
class String
{
public:
String( const char* pStr="")
{
if(pStr==NULL)
{
_pStr=new char[1];
_pStr='\0';
}
else
{ _pStr=new char[strlen(pStr)+1];
strcpy(_pStr,pStr);
}
}
String(const String& s)
:_pStr(new char[strlen(s._pStr)+1])
{
strcpy(_pStr,s._pStr);
}
String& operator=(const String& s)
{
if(this!=&s)
{
char*tmp=new char[strlen(s._pStr)+1];
delete[]_pStr;
strcpy(tmp,s._pStr);
_pStr=tmp;
}
return *this;
}
~String()
{
if(_pStr!=NULL)
{
delete[]_pStr;
_pStr=NULL;
}
}
private:
char *_pStr;
};
class String
{
public:
String(const char* pStr="")
{
if(pStr==NULL)
{
_pStr=new char[1];
*_pStr='\0';
}
else
{
_pStr=new char[strlen(pStr)+1];
strcpy(_pStr,pStr);
}
}
String(const String& s)
{
String tmp(s._pStr);
std::swap(tmp._pStr,_pStr);
}
String& operator=( String s)
{
std::swap(_pStr,s._pStr);
return *this;
}
friend ostream& operator<
#include
#include
using namespace std;
class String
{
public:
String(const char*pStr="")
{
if(pStr==NULL)
{
_pStr=new char[5];
*(_pStr+4)='\0';
}
else
{
_pStr=new char[strlen(pStr)+5];
_pStr=_pStr+4;
}
strcpy(_pStr,pStr);
Getcount()=1;
}
String(const String&s)
:_pStr(s._pStr)
{
Getcount()++;
}
String& operator=(const String&s)
{
_pStr=s._pStr;
Getcount()++;
return *this;
}
~String()
{
--Getcount();
if(Getcount()==0)
{
delete[]_pStr;
_pStr=NULL;
}
}
int& Getcount()
{
return*(int*)(_pStr-4);
}
friend ostream& operator<