include
include
class MyString {
private:
char* m_data; // 核心数据
int m_length;
public:
// 1. 普通构造函数
MyString(const char* str = nullptr) {
if (str == nullptr) {
m_length = 0;
m_data = new char[1];
*m_data = '\0'; // 空字符串
} else {
m_length = strlen(str);
m_data = new char[m_length + 1]; // +1 是为了存 '\0'
strcpy(m_data, str);
}
}
// 2. 拷贝构造函数 (深拷贝!)
MyString(const MyString& other) {
m_length = other.m_length;
m_data = new char[m_length + 1]; // 分配新内存
strcpy(m_data, other.m_data); // 复制内容
std::cout << "Deep copy called" << std::endl;
}
// 3. 析构函数
~MyString() {
if (m_data) {
delete[] m_data; // 对应 new[]
m_data = nullptr;
}
}
// 4. 赋值运算符重载 (=)
MyString& operator=(const MyString& other) {
// 自我赋值检测 (必须有!)
if (this == &other) {
return *this;
}
// 先释放旧内存
delete[] m_data;
// 再深拷贝新内容
m_length = other.m_length;
m_data = new char[m_length + 1];
strcpy(m_data, other.m_data);
return *this; // 返回引用支持连等 a=b=c
}
// 用于打印
const char* c_str() const { return m_data; }
};
int main() {
MyString s1("Hello");
MyString s2 = s1; // 调用拷贝构造
MyString s3;
s3 = s1; // 调用赋值运算符
// 观察 s1, s2, s3 的地址,确认它们的数据区 m_data 是不同的地址
}
浙公网安备 33010602011771号