洛阳市网站建设_网站建设公司_数据备份_seo优化
2025/12/30 14:07:18 网站建设 项目流程

题目:

实现自定义String类中的成员函数

class MyString { public: MyString(const char* str = nullptr); MyString(const MyString& other); MyString& operator=(const MyString& other); ~MyString(); private: char* _str; size_t _length; };

重点:

1.深拷贝

2.拷贝赋值运算符要处理自赋值

// 1. 带默认参数的构造函数实现 MyString::MyString(const char* str) : _length(0) { if (str == nullptr) { _str = new char[1]; _str[0] = '\0'; } else { _length = strlen(str); _str = new char[_length + 1]; strcpy(_str, str); } } // 2. 拷贝构造函数实现 MyString::MyString(const MyString& other) { _length = other._length; _str = new char[_length + 1]; strcpy(_str, other._str); } // 3. 拷贝赋值运算符重载实现 MyString& MyString::operator=(const MyString& other) { // 处理自赋值 if (this == &other) { return *this; } // 释放当前对象已有内存 delete[] _str; // 深拷贝 _length = other._length; _str = new char[_length + 1]; strcpy(_str, other._str); // 返回当前对象引用 return *this; } // 4. 析构函数实现 MyString::~MyString() { delete[] _str; _str = nullptr; }

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询