類string的構造函數&析構函數&賦值函數

class String
{
public:
String(const char *str=NULL); //普通構造函數
String(const String &other);  //複製構造函數
~String();                     //析構函數
String & operator=(const String &other);// 賦值函數

private:
char *m_String;                //私有成員,保存字符串 ;
};

String::~String(void)
{
if(m_String!=NULL)
{
delete m_String;
m_String=NULL;

}
}

String::String(const char *str)
{
if(str==NULL)
{
m_String=new char[1];
*m_String='/0';
}
else
{
m_String=new char[strlen(str)+1];
strcpy(m_String,str);
}
}

String::String(const String &other)
{
m_String=new char[strlen(other.m_String)+1];
strcpy(m_String,other.m_String );
}

String & String::operator=(const String &other)
{
if(this==&other)
return *this;
delete[] m_String;
m_String=new char[strlen(other.m_String)+1];
strcpy(m_String,other.m_String);

return *this;

}


注:1、賦值函數是對一個已經初始化的對象進行operator=操作:class A;
                                                                                                      A a;
                                                                                                      A b;
                                                                                                      b=a; //賦值函數調用


             首先判斷當前對象與引用傳遞對象是否是同一個對象,if yes,不做操作,直接返回;否則,先釋放當前對象的堆內存,然後再分              配足夠大小長度的堆內存複製對象;
    2、複製函數是一個對象初始化一塊內存區域,即新對象的內存區:
class A;
                                                                                                           A a;
                                                                                                           A b=a;       //複製構造函數調用
                                                                                                           A  b(a); //複製構造函數調用
                  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章