string类,浅拷贝,深拷贝(简洁版),写时拷贝

#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");
}





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值