c++的String类的简单实现(可优化)

大耗子 2020年02月23日 381次浏览

c++内的String类实现,在内存申请上,可以优化

#include <iostream>
using namespace std;
class String
{
private:
	char* str=NULL;
public:
	String(char* newstr = "")
	{
		if (newstr != NULL)
		{
			int len = strlen(newstr) + 1;
			str = new char[len];
			memcpy(str, newstr, len);
		}
	}
	String(String const& src)
	{
		int len = strlen(src.str) + 1;
		str = new char[len];
		memcpy(str, src.str, len);
	}
	~String()
	{
		cout << "I am xigou" << endl;
		if (str)
			delete str;
	}
public:
	String& operator =(String const& newstr)
	{
		if (this != &newstr)
		{
			if (str)
				delete str;
			int len = strlen(newstr.str) + 1;
			str = new char[len];
			memcpy(str, newstr.str, len);
		}
		return *this;
	}
	String& operator =(char* newstr)
	{
		if (str)
			delete str;
		int len = strlen(newstr) + 1;
		str = new char[len];
		memcpy(str, newstr, len);
		return *this;
	}
	bool operator ==(String const& newstr)
	{
		char* tempstr = str;
		char* tempnew = newstr.str;
		for (; *tempstr != '\0'; tempstr++, tempnew++)
		{
			if (*tempstr != *tempnew)
				return false;
		}
		return true;
	}
	String operator +(String const& newstr)
	{
		String temp;
		int len = strlen(this->str) + strlen(newstr.str) + 1;
		temp.str=new char[len];
		strcpy(temp.str, this->str );
		strcat(temp.str, newstr.str);
		return temp;
	}
	String& operator +=(String const& newstr)
	{
		int len = strlen(this->str) + strlen(newstr.str) + 1;
		String temp;
		temp.str=new char[len];
		strcpy(temp.str, this->str);
		strcat(temp.str, newstr.str);
		if (this->str)
			delete this->str;
		this->str = new char[len];
		strcpy(this->str, temp.str);
		return *this;
	}
	char& operator [](int index)
	{
		return str[index];
	}
	friend ostream& operator <<(ostream &os, String const& src)
	{
		os << src.str;
		return os;
	}
	friend istream& operator >>(istream &is, String &src)
	{
		char temp[100];
		is >> temp;
		if (src.str)
			delete src.str;
		int len = strlen(temp) + 1;
		src.str = new char[len];
		memcpy(src.str, temp, len);
		return is;
	}
public:
	void show()
	{
		cout << str << endl;
	}
	int lenght()
	{
		return strlen(str);
	}
};