#include<iostream>
#include<stdio.h>
#include<stdlib.h>
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<<(ostream& _cout,const String&s)
{
_cout<<s._pStr;
return _cout;
}
private:
char*_pStr;
};
void main()
{
String s1="hello";
String s2(s1);
String s3;
s3=s1;
cout<<s1<<endl;
cout<<s2<<endl;
cout<<s3<<endl;
system("pause");
}
写时拷贝
#include<iostream>
#include<stdlib.h>
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<<(ostream& _cout,const String&s)
{
_cout<<s._pStr;
return _cout;
}
private:
char*_pStr;
};
void main()
{
String s1="hello";
String s2(s1);
String s3;
s3=s1;
cout<<s1<<endl;
cout<<s2<<endl;
cout<<s3<<endl;
cout<<s1.Getcount()<<endl;
cout<<s2.Getcount()<<endl;
cout<<s3.Getcount()<<endl;
/*cout<<s3<<endl;*/
system("pause");
}