用c++写一个新的string类包含成员插入*p,并重载基本运算符
时间: 2024-02-13 21:01:30 浏览: 32
好的,以下是一个示例代码:
```c++
#include <iostream>
#include <cstring>
class MyString {
public:
MyString() : ptr(nullptr), len(0) {}
MyString(const char* str) {
len = std::strlen(str);
ptr = new char[len + 1];
std::strcpy(ptr, str);
}
MyString(const MyString& other) {
len = other.len;
ptr = new char[len + 1];
std::strcpy(ptr, other.ptr);
}
~MyString() {
if (ptr != nullptr) {
delete[] ptr;
ptr = nullptr;
}
}
MyString& operator=(const MyString& rhs) {
if (this != &rhs) {
if (ptr != nullptr) {
delete[] ptr;
}
len = rhs.len;
ptr = new char[len + 1];
std::strcpy(ptr, rhs.ptr);
}
return *this;
}
MyString operator+(const MyString& rhs) const {
MyString result;
result.len = len + rhs.len;
result.ptr = new char[result.len + 1];
std::strcpy(result.ptr, ptr);
std::strcat(result.ptr, rhs.ptr);
return result;
}
MyString& operator+=(const MyString& rhs) {
len += rhs.len;
char* temp = new char[len + 1];
std::strcpy(temp, ptr);
std::strcat(temp, rhs.ptr);
delete[] ptr;
ptr = temp;
return *this;
}
char& operator[](int index) {
return ptr[index];
}
void insert(const char* str, int pos) {
int str_len = std::strlen(str);
char* temp = new char[len + str_len + 1];
std::strncpy(temp, ptr, pos);
std::strcpy(temp + pos, str);
std::strcpy(temp + pos + str_len, ptr + pos);
delete[] ptr;
ptr = temp;
len += str_len;
}
friend std::ostream& operator<<(std::ostream& os, const MyString& str);
private:
char* ptr;
int len;
};
std::ostream& operator<<(std::ostream& os, const MyString& str) {
os << str.ptr;
return os;
}
int main() {
MyString s1 = "Hello";
MyString s2 = "World";
std::cout << s1 << std::endl;
std::cout << s2 << std::endl;
s1 += s2;
std::cout << s1 << std::endl;
s1.insert(" ", 5);
std::cout << s1 << std::endl;
std::cout << s1[11] << std::endl;
return 0;
}
```
这个 `MyString` 类包含了成员函数 `insert` 来插入一个字符串到指定位置,同时重载了 `+` 和 `+=` 运算符来支持字符串的拼接,还重载了 `[]` 运算符来支持访问字符串的某个字符。同时,还重载了 `<<` 运算符来支持输出该字符串类对象。