现在的位置: 首页 > 综合 > 正文

string类实现

2013年11月12日 ⁄ 综合 ⁄ 共 1325字 ⁄ 字号 评论关闭
#include <iostream>
#include <string>
using namespace std;
class String
{
public:
	String();
	String(const char * src);
	String(String & src);
	~String();
	void operator = (String& sub);
	String operator + (String sub);

	char * ToString();
	int GetLen();
private:
	char * str;
	int len;
};

String::String()
{
	len = 0;
	str = NULL;
}


String::String(const char * src)
{
	if(src == NULL)
		return;
	len = strlen(src);
	str = new char[len+1];
	strcpy(str,src);
}

String::String(String & src)
{
	len = src.GetLen();

	cout<<"src的长度是:"<<len<<endl;
	cout<<"src的内容是:"<<src.ToString()<<endl;

	if(len != 0)
	{
		str = new char[len+1];
		strcpy(str,src.ToString());
		cout<<"内容拷贝成功"<<endl;
	}
}

String::~String()
{
	delete []str;
	str = NULL;
	len = 0;
}

int String::GetLen()
{
	return len;
}

char * String::ToString()
{
	return str;
}

void String::operator = (String& other)
{
	int sublen = other.GetLen();
	if(sublen != 0)
	{
		str = new char[len+1];
		strcpy(str,other.ToString());
		len = sublen;
	}
}

String String::operator + (String sub)
{
	cout<<"phase 1"<<endl;

	int newLen=len+sub.GetLen();
	char * newstr = new char[newLen+1];

	strcpy(newstr,str);
	strcat(newstr,sub.ToString());

	cout<<"phase 2"<<endl;

	String newString(newstr);

	cout<<"phase 3"<<endl;

	return newString;
}


void main()
{
	String a;
	String b("hello world");
	cout<<"b的长度是:"<<b.GetLen()<<endl;
	cout<<"b的内容是:"<<b.ToString()<<endl;

	String c = b;
	cout<<"c的长度是:"<<c.GetLen()<<endl;
	cout<<"c的内容是:"<<c.ToString()<<endl;

	String d = b+c;

	cout<<"d的长度是:"<<d.GetLen()<<endl;
	cout<<"d的内容是:"<<d.ToString()<<endl;
}

抱歉!评论已关闭.