mstring.h

来自「上传几个数据结构源代码」· C头文件 代码 · 共 69 行

H
69
字号
#include"iostream.h"
#include"string.h"
class String
{
private:
	char* pData;
	int nLength;
public:
	String(String& p)
	{
		nLength=p.nLength;
		pData=new char[nLength];
		strcpy(pData,p.pData);
	}
	String()
	{
		nLength=0,pData=NULL;
	}
	String(const char* str)
	{
   nLength=strlen(str)+1;
   pData=new char[nLength];
   strcpy(pData,str);
	}
	~String()
	{
		if(pData) delete pData;
	}
	String& operator=(const String& op)
	{
		if(&op==this)
			return *this;
		if(nLength!=op.nLength)
		{
			nLength=op.nLength;
			delete pData;
			pData=new char[nLength];
		}
		strcpy(pData,op.pData);
		return *this;
	}
	friend String operator+(const String& pa,const String& pb)
	{
		String sp;
		sp.nLength=pa.nLength+pb.nLength-1;
		sp.pData=new char[sp.nLength];
		strcpy(sp.pData,pa.pData);
		for(int i=pa.nLength-1;i<sp.nLength;i++)
			sp.pData[i]=pb.pData[i-(pa.nLength-1)];
		sp.pData[sp.nLength-1]='\0';
		return sp;
	}
	friend ostream& operator<<(ostream& out,const String& op)
	{
		out<<op.pData;
		return out;
	}
	friend istream& operator>>(istream& in,String& op)
	{
		char p[50];
		in>>p;
		op.nLength=strlen(p)+1;
        delete op.pData;
		op.pData=new char[op.nLength];
		strcpy(op.pData,p);
		return in;
	}

};

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?