1. 程式人生 > >【C++筆記】編寫類string的建構函式、解構函式和賦值函式

【C++筆記】編寫類string的建構函式、解構函式和賦值函式

#include<iostream>
using namespace std;
class String
{
public:
	String(const char *str=NULL);            //普通建構函式
	String(const String &other);             //複製建構函式
	~String(void);                           //解構函式
	String & operator=(const String &other);//賦值函式
private:
	char *m_String;                        //私有成員,儲存字串
};
String::String(const char *str)
{
	cout<<"普通建構函式"<<endl;
	if(str==NULL)                         //如果str為空,存空字串
	{
		m_String=new char[1];             //分配一個位元組
		*m_String='\0';                  //將之賦值為字串結束符
	}
	else
	{
		m_String=new char[strlen(str)+1]; //分配空間容納str內容
		strcpy(m_String,str);             //賦值str到私有成員 
	}
}
String::String(const String &other)
{
	cout<<"複製建構函式"<<endl;
	m_String=new char[strlen(other.m_String)+1];
	strcpy(m_String,other.m_String);
}
String::~String(void)
{
	cout<<"解構函式"<<endl;
	if(m_String!=NULL)                    //如果m_String 不為NULL,釋放堆記憶體
	{
		delete [] m_String;              //釋放後置為NULL
		m_String=NULL;
	}
}
String & String::operator =(const String &other)
{
	cout<<"賦值函式"<<endl;
	if(this==&other)                   //如果物件與other是同一個物件
	{
		return *this;                  //直接返回本身
	}
	delete [] m_String;
	m_String=new char[strlen(other.m_String)+1];
	strcpy(m_String,other.m_String);
	return *this;
}
int main()
{
	String a("hello");           //呼叫普通建構函式
	String b("word");            //呼叫普通建構函式
	String c(a);                 //呼叫複製建構函式
	c=b;                         //呼叫賦值函式
	return 0;
}

說明: (1)普通建構函式:這裡判斷了傳入的引數是否為NULL,如果是NULL,初始化一個位元組的空字串(包括結束符'\0');如果不是,分配足夠大小長度的堆記憶體來儲存字串。 (2)複製構造:只是分配足夠小長度的堆記憶體來儲存字串。 (3)解構函式:如果類私有成員m_String不為NULL,釋放m_String指向的堆記憶體,並且為了避免產生野指標,將m_String賦值為NULL。 (4)賦值函式:首先判斷當前物件與引用傳遞物件是否是同一個物件,如果是,不做操作,直接返回;否則,先釋放當前物件的堆記憶體,然後分配足夠大小長度的堆記憶體複製字串。