实现一个string类
时间: 2024-05-23 20:09:47 浏览: 17
好的,您想了解如何实现一个string类。实际上,一个string类的实现可以非常复杂,因为它需要处理许多不同类型的操作,例如字符串拼接、比较、搜索等。不过,我可以给您提供一个简单的实现示例,以便您了解基本原理。以下是一个简单的string类的实现,供您参考:
class MyString {
private:
char* mData; // 存储字符串的内存空间
int mSize; // 字符串的长度
public:
// 构造函数
MyString(): mData(nullptr), mSize(0) {}
MyString(const char* str){
mSize = strlen(str);
mData = new char[mSize + 1];
strncpy(mData, str, mSize + 1);
}
// 析构函数
~MyString(){
if (mData != nullptr) {
delete[] mData;
}
}
// 拷贝构造函数
MyString(const MyString& other) {
mSize = other.mSize;
mData = new char[mSize + 1];
strncpy(mData, other.mData, mSize + 1);
}
// 赋值运算符
MyString& operator=(const MyString& other) {
if (this != &other) {
// 先删除旧的数据
if (mData != nullptr) {
delete[] mData;
}
// 然后拷贝新的数据
mSize = other.mSize;
mData = new char[mSize + 1];
strncpy(mData, other.mData, mSize + 1);
}
return *this;
}
// 重载[]运算符
char& operator[](int index) {
assert(index >= 0 && index < mSize);
return mData[index];
}
// 重载+运算符
MyString operator+(const MyString& other) {
MyString result;
result.mSize = mSize + other.mSize;
result.mData = new char[result.mSize + 1];
strncpy(result.mData, mData, mSize);
strncpy(result.mData + mSize, other.mData, other.mSize + 1);
return result;
}
// 重载==运算符
bool operator==(const MyString& other) const {
if (mSize != other.mSize) {
return false;
}
return strcmp(mData, other.mData) == 0;
}
// 重载!=运算符
bool operator!=(const MyString& other) const {
return !(*this == other);
}
// 获取字符串长度
int size() const {
return mSize;
}
// 获取C风格字符串指针
const char* c_str() const {
return mData;
}
};
这个实现比较基础,但已经包含了一些常见的操作,例如构造函数、析构函数、拷贝构造函数、赋值运算符、重载[]运算符、重载+运算符、重载==运算符、重载!=运算符、size()函数以及c_str()函数。当然,在实际应用中,您可能需要根据具体需求进行适当的优化和扩展。