類String的構造函數、拷貝構造函數、析構函數、賦值函數

要求:編寫類String的構造函數、析構函數和賦值函數

class String 
{ 
public: 
     String(const char *str = NULL);// 普通構造函數 
     String(const String &other);    // 拷貝構造函數 
     ~ String(void);    // 析構函數 
     String & operator =(const String &other);// 賦值函數 
private: 
     char *m_data;// 用於保存字符串 
};

 

結果:

//普通構造函數 
String::String(const char *str) 
{ 
        if(str==NULL) 
        { 
                m_data = NULL;
        }    
        else 
        { 
         int length = strlen(str); 
         m_data = new char[length+1];
         strcpy(m_data, str); 
        } 
} 
// String的析構函數 
String::~String(void) 
{ 
    if(m_data)
    {
        delete [] m_data; 
    }
 } 
//拷貝構造函數 
String::String(const String &other)    
{     
    m_data = new char[strlen(other.m_data) + 1];     
    strcpy(m_data, other.m_data);    
} 
//賦值函數 
String & String::operator =(const String &other) 
{     
        if(this != &other)                    
        {
            if(m_data)
            {
                delete [] m_data; 
            }
            m_data = new char[strlen( other.m_data )+1];   
            strcpy( m_data, other.m_data );   
        }   
        return *this; 
}

 

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