仿照标准字符串类string,设置一个自己的字符串类
时间: 2024-03-25 14:40:45 浏览: 82
创建一个字符串类
好的,我可以为您提供一个简单的自定义字符串类的示例代码:
```cpp
#include <iostream>
#include <cstring>
class MyString {
private:
char* str;
int length;
public:
MyString() {
length = 0;
str = new char[1];
str[0] = '\0';
}
MyString(const char* s) {
length = std::strlen(s);
str = new char[length + 1];
std::strcpy(str, s);
}
MyString(const MyString& other) {
length = other.length;
str = new char[length + 1];
std::strcpy(str, other.str);
}
~MyString() {
delete[] str;
}
MyString& operator=(const MyString& other) {
if (this != &other) {
delete[] str;
length = other.length;
str = new char[length + 1];
std::strcpy(str, other.str);
}
return *this;
}
MyString operator+(const MyString& other) const {
MyString result;
result.length = length + other.length;
delete[] result.str;
result.str = new char[result.length + 1];
std::strcpy(result.str, str);
std::strcat(result.str, other.str);
return result;
}
bool operator==(const MyString& other) const {
return std::strcmp(str, other.str) == 0;
}
bool operator!=(const MyString& other) const {
return !(*this == other);
}
char& operator[](int index) {
return str[index];
}
const char& operator[](int index) const {
return str[index];
}
int size() const {
return length;
}
const char* c_str() const {
return str;
}
friend std::ostream& operator<<(std::ostream& os, const MyString& s) {
os << s.str;
return os;
}
};
int main() {
MyString s1("Hello");
MyString s2("World");
MyString s3 = s1 + s2;
std::cout << s3 << std::endl;
std::cout << s3.size() << std::endl;
std::cout << s3.c_str() << std::endl;
return 0;
}
```
这个自定义字符串类包含了一些常见的操作符重载和成员函数,例如构造函数、析构函数、复制构造函数、赋值运算符、加法运算符、比较运算符、下标运算符、size函数和c_str函数等。
阅读全文