自定義 C++ 字符串類 CString 存在多個嚴重問題:構造函數初始化錯誤、索引運算符語法錯誤、析構函數釋放棧內存導致崩潰。
class CString {
char m_buff[MAXLENGTH]; // 固定大小數組,棧上分配
public:
CString() { m_buff[0] = NULL; } // 應用 '\0' 而非 NULL
char operator const; // 語法錯誤,缺少參數列表和索引變量
~CString() { delete[] m_buff; } // 嚴重錯誤:棧內存不能用 delete[] 釋放
};
char* m_data 指向堆內存this == &otherclass 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;
}
};
std::unique_ptr 或 std::string 替代手動內存管理size()、c_str() 等常用成員函數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;
}