首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 字符串類設計:構造函數、拷貝構造、賦值運算符與析構函數完整實現

     編輯:程式設計綜合問答

問題背景

自定義 C++ 字符串類 CString 存在多個嚴重問題:構造函數初始化錯誤、索引運算符語法錯誤、析構函數釋放棧內存導致崩潰。

原代碼關鍵錯誤

class CString {
    char m_buff[MAXLENGTH];  // 固定大小數組,棧上分配
public:
    CString() { m_buff[0] = NULL; }  // 應用 '\0' 而非 NULL
    
    char operator const;  // 語法錯誤,缺少參數列表和索引變量
    
    ~CString() { delete[] m_buff; }  // 嚴重錯誤:棧內存不能用 delete[] 釋放
};

正確的字符串類設計原則

  1. 動態內存管理:使用 char* m_data 指向堆內存
  2. 三大函數:拷貝構造函數、賦值運算符、析構函數必須成對實現
  3. 深拷貝:避免多個對象共享同一塊內存導致雙重釋放
  4. 自賦值檢查:賦值運算符中檢查 this == &other

標準實現模式

class MyString {
private:
    char* m_data;
    
public:
    // 普通構造函數
    MyString(const char* str = nullptr) {
        if (str == nullptr) {
            m_data = new char[1];
            *m_data = '\0';
        } else {
            int len = strlen(str);
            m_data = new char[len + 1];
            strcpy(m_data, str);
        }
    }
    
    // 拷貝構造函數
    MyString(const MyString& other) {
        int len = strlen(other.m_data);
        m_data = new char[len + 1];
        strcpy(m_data, other.m_data);
    }
    
    // 析構函數
    ~MyString() { delete[] m_data; }
    
    // 賦值運算符
    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;
    }
    
    // 索引運算符(可選)
    char& operator[](size_t index) { return m_data[index]; }
    const char& operator[](size_t index) const { return m_data[index]; }
    
    // 輸出運算符(友元函數)
    friend std::ostream& operator<<(std::ostream& os, const MyString& s) {
        return os << s.m_data;
    }
};

現代 C++ 改進建議

  • 使用 std::unique_ptr 或 std::string 替代手動內存管理
  • 實現移動語義(移動構造、移動賦值)提升性能
  • 添加 size()、c_str() 等常用成員函數
  • 考慮小字符串優化(SSO)避免短字符串堆分配

測試用例

int main() {
    MyString s1("Hello");
    MyString s2 = s1;        // 拷貝構造
    MyString s3(s1);         // 拷貝構造
    MyString s4;             // 默認構造
    s4 = s1;                 // 賦值運算符
    s4 = s4;                 // 自賦值測試
    std::cout << s1 << s2 << s3 << s4;
    return 0;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved