用cpp写出string的+=重载
时间: 2023-12-17 12:04:17 浏览: 32
下面是用 C++ 实现 string 的 += 重载的代码示例:
```cpp
#include <iostream>
#include <cstring>
class MyString {
public:
MyString(const char* str = "") {
m_size = strlen(str);
m_capacity = m_size + 1;
m_data = new char[m_capacity];
strcpy(m_data, str);
}
~MyString() {
delete[] m_data;
}
MyString& operator+=(const MyString& rhs) {
size_t new_size = m_size + rhs.m_size;
if (new_size + 1 > m_capacity) {
m_capacity = new_size + 1;
char* new_data = new char[m_capacity];
strcpy(new_data, m_data);
delete[] m_data;
m_data = new_data;
}
strcat(m_data, rhs.m_data);
m_size = new_size;
return *this;
}
const char* c_str() const {
return m_data;
}
private:
char* m_data;
size_t m_size;
size_t m_capacity;
};
int main() {
MyString str1("hello");
MyString str2(" world");
str1 += str2;
std::cout << str1.c_str() << std::endl;
return 0;
}
```
在这个示例中,我们首先定义了一个 MyString 类,其中包含了字符串的数据、大小和容量等信息,同时还重载了 += 运算符。在 += 运算符中,我们首先计算出新字符串的大小,如果新字符串的大小超过了原有容量,则重新分配内存空间,同时将原有数据复制到新的内存空间中。然后使用 strcat 函数将两个字符串拼接起来,最后更新字符串的大小并返回 this 指针。
在 main 函数中,我们定义了两个字符串 str1 和 str2,将它们拼接起来,并输出结果。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)