用cpp定义一个字符串类
时间: 2023-05-29 20:07:38 浏览: 71
以下是一个简单的字符串类的定义,包括构造函数、析构函数、拷贝构造函数、赋值运算符、字符串连接运算符、字符串比较运算符、字符串长度函数等。
```cpp
#include <cstring>
class String {
public:
String() : data(nullptr), length(0) {}
String(const char* s) : data(new char[strlen(s) + 1]), length(strlen(s)) {
strcpy(data, s);
}
String(const String& other) : data(new char[other.length + 1]), length(other.length) {
strcpy(data, other.data);
}
~String() {
delete[] data;
}
String& operator=(const String& other) {
if (this != &other) {
delete[] data;
data = new char[other.length + 1];
length = other.length;
strcpy(data, other.data);
}
return *this;
}
String operator+(const String& other) const {
String result;
result.data = new char[length + other.length + 1];
result.length = length + other.length;
strcpy(result.data, data);
strcat(result.data, other.data);
return result;
}
bool operator==(const String& other) const {
if (length != other.length)
return false;
return strcmp(data, other.data) == 0;
}
bool operator!=(const String& other) const {
return !(*this == other);
}
int size() const {
return length;
}
private:
char* data;
int length;
};
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)