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

函數原型

class String
{
public:
    String(const char* str = "");
    ~String();
    String(const String& other);
    String&::operator=(const String& other);
};

String的普通構造函數

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

String的析構函數

String::~String()
{
    delete []m_data;
}

String的拷貝構造函數

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

// 賦值函數
String&::operator=(const String& other)
{
    // 1.判斷是否是自賦值
    if (this != other)
    {
        // 2.分配新的內存
        char* temp = new char[strlen(other.m_data) + 1];
        strcpy(temp,other.m_data);
        // 3.釋放舊資源,並指向新的資源
        delete []m_data;
        m_data = temp;
    }
    // 4.返回對象
    return *this;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章