【C++】String類及其優化版的實現

#include<iostream>
using namespace std;
class String
{
public:
	String()
	{
		_ptr = new char[1];
		_ptr[0] = 0;
	}
	String(const char* str)
	{
		_ptr = new char[strlen(str)+1];
		strcpy(_ptr,str);
	}
	String(const String& str)
	 {
		_ptr = new char[strlen(str._ptr)+1];
		strcpy(_ptr,str._ptr);
	 }
	String& operator =(const String& str )
	{
		if(this != &str)
		{
			delete []_ptr;
			_ptr = new char[strlen(str._ptr)+1];
			strcpy(_ptr,str._ptr );
		}
		return *this;
	}
	~String()
	{
		delete []_ptr;
	}
	char* GetStr()
	{
		return _ptr;
	}

private:
	char* _ptr;
};

int main()
{	
	String s1;
	cout<<"s1:"<<s1.GetStr()<<endl;
	String s2("abcd");
	cout<<"s2:"<<s2.GetStr()<<endl;
	String s3("1234");
	cout<<"s3:"<<s3.GetStr()<<endl;
	String s4(s2);
	cout<<"s4:"<<s4.GetStr()<<endl;
	s2 = s3;
	cout<<"s2:"<<s2.GetStr()<<endl;
	getchar();
	return 0;
}


String的優化版

#include <iostream>
using namespace std;

class String
{
public:
	String(char* str)
		:_ptr(new char[strlen(str) + 1])
	{
		strcpy(_ptr, str);
	}

	void Swap(String& s)
	{
		char* tmp = s._ptr;
		s._ptr = _ptr;
		_ptr = tmp;
	}

	String(const String& s)
		:_ptr(NULL)
	{
		String tmp(s._ptr);
		Swap(tmp);
	}

	//String& operator=(const String& s)
	//{
	//	if (this != &s)
	//	{
	//		String tmp(s._ptr);
	//		this->Swap(tmp);
	//	}

	//	return *this;
	//}

	String& operator=(String s)
	{
      //
		Swap(s);

		return *this;
	}

	//String& operator=(const String& s)
	//{
	//	if (this != &s)
	//	{
	//		delete [] _ptr;
	//		_ptr = new char[strlen(s._ptr) + 1];
	//		strcpy(_ptr, s._ptr);
	//	}

	//	return *this;
	//}


	~String()
	{
		if (_ptr)
		{
			delete[] _ptr;
		}
	}

	// 四個默認成員函數 + operator[]
	char* GetStr()
	{
		return _ptr;
	}

private:
	char* _ptr;
};

int main()
{
	String s1("abcd");
	String s2(s1);
	String s3("efghs");
	s3 = s2;
	s2 = s2;

	cout<<"s1:"<<s1.GetStr()<<endl;
	cout<<"s2:"<<s2.GetStr()<<endl;
	cout<<"s3:"<<s3.GetStr()<<endl;

	return 0;
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章