1. 程式人生 > >實現一個string類,包括構造、析構、拷貝構造及operator= 函式

實現一個string類,包括構造、析構、拷貝構造及operator= 函式

#include "MyString.h"
#include <string>

//MyString::MyString(void)
//{
//	m_data = new char[1];  
//	*m_data='\0';  
//	//m_data = NULL;		//這樣也行吧?
//}

MyString::MyString(const char *str)
{
	if (str == NULL)
	{  
		m_data = new char[1];  
		*m_data='\0';  
	}
	else
	{  
		int len=strlen(str);  
		m_data = new char[len+1];  
		strcpy(m_data,str);  
	} 
}

MyString::MyString(const MyString &other)
{
	int len = strlen(other.m_data);  
	m_data = new char[len+1];  
	strcpy(m_data,other.m_data);  
}

MyString::~MyString(void)
{
	delete []m_data;
	m_data = NULL;
}

MyString& MyString::operator=(const MyString &other)
{
	if (this == &other)  
		return *this;  

	delete []m_data;

	int len = strlen(other.m_data);  
	m_data = new char[len+1];  
	strcpy(m_data,other.m_data);  

	return *this;
}

bool MyString::operator==(const MyString& str)
{
	 return strcmp(m_data,str.m_data) == 0;
}

//注意友元函式定義時不要friend,而且不要MyString::
ostream& operator<<(ostream& o,const MyString& str)
{
	o<<str.m_data;  
	return o; 
}

#include "MyString.h"

void main(void)
{
	MyString s1 = "hello";  
	MyString s2 = s1;	//這是物件初始化,等效於MyString s2(s1),會呼叫類的拷貝建構函式
	MyString s3;
	s3 = s1;		//這是賦值,注意與MyString s2 = s1;不同,會呼叫 =過載函式
	MyString s4 = "hello";  
	cout<<"s1 = "<<s1<<endl;  
	cout<<"s2 = "<<s2<<endl;  
	cout<<boolalpha<<(s4 == s1)<<endl;

	getchar();
}

執行結果: