用C++完成下面程序:设计一个字符串类重载“+=”的运算符,使其实现两个字符串的连接并赋值。使用成员函数
时间: 2024-02-15 15:04:49 浏览: 42
以下是用C++实现字符串类重载“+=”运算符的代码:
```c++
#include <iostream>
#include <cstring>
class String {
private:
char* str;
int len;
public:
String() : len(0), str(nullptr) {}
String(const char* s) : len(std::strlen(s)), str(new char[len + 1]) {
std::strcpy(str, s);
}
String(const String& s) : len(s.len), str(new char[len + 1]) {
std::strcpy(str, s.str);
}
~String() {
delete[] str;
}
String& operator+=(const String& s) {
char* temp = new char[len + s.len + 1];
std::strcpy(temp, str);
std::strcat(temp, s.str);
len += s.len;
delete[] str;
str = temp;
return *this;
}
const char* c_str() const {
return str;
}
};
int main() {
String s1("Hello"), s2("World");
s1 += s2;
std::cout << s1.c_str() << std::endl; // 输出:HelloWorld
return 0;
}
```
在上面的代码中,我们定义了一个名为“String”的字符串类,其中包含一个指向字符数组的指针“str”和一个表示字符串长度的整数“len”。我们使用了标准C++库中的函数来处理字符串,如std::strlen()、std::strcpy()和std::strcat()等。
在String类中,我们重载了“+=”运算符,使其能够连接两个字符串并将结果赋值给调用对象。我们还提供了一个名为“c_str()”的成员函数,以便在需要时返回字符串的C风格表示形式。
在主函数中,我们创建了两个String对象“s1”和“s2”,并使用“+=”运算符将它们连接起来。最后,我们使用“c_str()”函数将连接后的字符串打印到屏幕上。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)