请设计实现自己的字符串类(不要直接用系统 的string)自行设计补充 类中列出的方法的返回值,参数等自行设计实 现。
时间: 2023-05-28 11:05:26 浏览: 112
设计实现的字符串类如下:
```c++
class MyString {
public:
MyString(); // 默认构造函数
MyString(const char* str); // 带参构造函数
MyString(const MyString& other); // 拷贝构造函数
~MyString(); // 析构函数
MyString& operator=(const MyString& other); // 赋值运算符重载
MyString operator+(const MyString& other) const; // 加法运算符重载
bool operator==(const MyString& other) const; // 等于运算符重载
bool operator!=(const MyString& other) const; // 不等于运算符重载
bool operator<(const MyString& other) const; // 小于运算符重载
bool operator<=(const MyString& other) const; // 小于等于运算符重载
bool operator>(const MyString& other) const; // 大于运算符重载
bool operator>=(const MyString& other) const; // 大于等于运算符重载
char& operator[](int index); // 下标运算符重载
const char& operator[](int index) const; // 下标运算符重载
int length() const; // 返回字符串长度
char* c_str() const; // 返回字符串的C风格表示
bool empty() const; // 返回字符串是否为空
void clear(); // 清空字符串
void resize(int len); // 调整字符串长度,新长度小于原长度时,截断字符串;新长度大于原长度时,填充'\0'
void append(const char* str); // 在字符串末尾追加一个C风格字符串
void append(const MyString& other); // 在字符串末尾追加另一个字符串
void insert(int pos, const char* str); // 在指定位置插入一个C风格字符串
void insert(int pos, const MyString& other); // 在指定位置插入另一个字符串
void erase(int pos, int len); // 删除从pos开始的len个字符
private:
char* m_data;
int m_size;
};
```
其中,`m_data`表示字符串的实际存储空间,`m_size`表示字符串的长度(不包括结尾的'\0'字符)。以下是对每个方法的详细解释:
- `MyString()`:默认构造函数,创建一个空字符串。
- `MyString(const char* str)`:带参构造函数,使用一个C风格字符串初始化字符串。
- `MyString(const MyString& other)`:拷贝构造函数,使用另一个字符串初始化字符串。
- `~MyString()`:析构函数,释放字符串的存储空间。
- `MyString& operator=(const MyString& other)`:赋值运算符重载,将一个字符串赋值给另一个字符串。
- `MyString operator+(const MyString& other) const`:加法运算符重载,将两个字符串拼接成一个新的字符串并返回。
- `bool operator==(const MyString& other) const`:等于运算符重载,比较两个字符串是否相等。
- `bool operator!=(const MyString& other) const`:不等于运算符重载,比较两个字符串是否不相等。
- `bool operator<(const MyString& other) const`:小于运算符重载,比较两个字符串的字典序大小。
- `bool operator<=(const MyString& other) const`:小于等于运算符重载,比较两个字符串的字典序大小。
- `bool operator>(const MyString& other) const`:大于运算符重载,比较两个字符串的字典序大小。
- `bool operator>=(const MyString& other) const`:大于等于运算符重载,比较两个字符串的字典序大小。
- `char& operator[](int index)`:下标运算符重载,访问字符串中指定位置的字符。
- `const char& operator[](int index) const`:下标运算符重载,访问字符串中指定位置的字符。
- `int length() const`:返回字符串的长度。
- `char* c_str() const`:返回字符串的C风格表示。
- `bool empty() const`:返回字符串是否为空。
- `void clear()`:清空字符串。
- `void resize(int len)`:调整字符串的长度,新长度小于原长度时,截断字符串;新长度大于原长度时,填充'\0'。
- `void append(const char* str)`:在字符串末尾追加一个C风格字符串。
- `void append(const MyString& other)`:在字符串末尾追加另一个字符串。
- `void insert(int pos, const char* str)`:在指定位置插入一个C风格字符串。
- `void insert(int pos, const MyString& other)`:在指定位置插入另一个字符串。
- `void erase(int pos, int len)`:删除从pos开始的len个字符。