c++ string 类的实现

#include <iostream> #include <string>
class CString
{
public:
	CString(const char *p = NULL)
	{
		if (p == NULL)
		{
			mptr = new char[1];
			*mptr = 0;
		}
		else
		{
			mptr = new char[strlen(p) + 1];
			strcpy(mptr, p);
		}
	}
	CString(const CString &src)
	{
		mptr = new char[strlen(src.mptr) + 1];
		strcpy(mptr, src.mptr);

	}
	CString& operator=(const CString &src)
	{
		if (this == &src)
		{
			return *this;
		}
		delete[]mptr;

		mptr = new char[strlen(src.mptr) + 1];
		strcpy(mptr, src.mptr);
		return *this;
	}
	~CString()
	{
		delete[]mptr;
		mptr = NULL;//2次调用
	}

	bool operator>(const CString &src)const
	{
		return strcmp(mptr, src.mptr)>0;
	}
	bool operator<(const CString &src)const
	{
		return strcmp(mptr, src.mptr) < 0;

	}
	bool operator==(const CString &src)const
	{
		return strcmp(mptr, src.mptr) == 0;
	}

	int size()const
	{
		return strlen(mptr);
	}
	char& operator[](unsigned int index)
	{
		if (index >= 0 && index <= strlen(mptr))
			return mptr[index];
	}
	const char* c_str()const
	{
		return mptr;
	}

	class iterator
	{
	public:
		iterator(char *p = NULL)
			:ptr(p){};

		bool  operator != (const iterator &it)
		{
			return ptr != it.ptr;
		}
		void operator++()
		{
			++ptr;
		}
		char& operator*()//
		{
			return *ptr;
		}

		char* ptr;// operator!=  operator++  operator*
	};

	iterator begin()
	{

		return iterator(mptr);
	
	}
	iterator end()
	{
		return iterator(mptr + strlen(mptr));

	}
	friend	ostream& operator<<(ostream &out, const CString &src);
	friend  CString operator+(const CString &left, const CString &right);
	friend istream& operator>>(istream &in, const CString &srcf);
private:
	char *mptr;

};
CString operator+(const CString &left, const CString &right)
{
	if (left.mptr == 0 || right.mptr == 0)
	{
		return left.mptr == 0 ? right.mptr : left.mptr;
	}
	char *ptem = new char[strlen(left.mptr) + strlen(right.mptr) + 1];
	strcpy(ptem, left.mptr);
	strcat(ptem, right.mptr);
	CString tem(ptem);
	delete[]ptem;
	return tem;
}
istream& operator>>(istream &in, CString &src)
{
	char temp[255];
	in >> setw(10) >> temp;
	src = temp; //使用赋值运算符
	return in;
}

ostream& operator<<(ostream &out, const CString &src)
{
	cout << src.mptr;
	return out;
}

int main(int argc, char* argv[])
{
	CString str1 = "Aha!";
	CString str2 = "My friend";
	CString str3 = str1 + str2;
	//cin >> str3;
	cout << str3 << "/n" << str3.size() << endl;

	str3 = str2 + "|";
	cout << str3 << endl;

	str1 = "|" + str2;
	cout << str1 << endl;
	str1 = str2 + str3;
	cout << str1 << endl;

	if (str1 > str2)  // > < ==
	{
		cout << "str1 > str2" << endl;
	}

	int size = str1.size();
	for (int i = 0; i < size; ++i)
	{
		cout << str1[i];
	}
	cout << endl;

	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38936579/article/details/79045965
今日推荐