实现方法有构造函数,拷贝构造函数,移动构造函数。析构函数,字符串相加,字符串赋值,字符串移动赋值。判断两个 类是否相同,运算符[]重载,输出运算符重载
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<stdlib.h>
using namespace std;
class MyString {
public:
char* str;
MyString(const char* stra) :str(nullptr) {
if (stra != nullptr) {
size_t len = strlen(stra)+1;
str = new char[len];
strncpy(str, stra, len);
}
}
MyString(const MyString& other) :str(nullptr) {
if(other.str!=nullptr){
size_t len = strlen(other.str)+1;
str = new char[len];
strncpy(str, other.str, len);
}
}
MyString(MyString&& other) :str(nullptr) {
str = other.str;
other.str = nullptr;
}
~MyString() {
delete[] str;
}
MyString operator+(const MyString& other) {
if (other.str != nullptr) {
MyString result(*this);
size_t len1 = strlen(str);
size_t len2 = strlen(other.str);
size_t len = len1 + len2 + 1;
delete[] result.str;
result.str = new char[len];
strcpy(result.str, "");
strcat(result.str, str);
strcat(result.str, other.str);
return result;
}
return *this;
}
MyString& operator=(const MyString& other) {
if (this != &other) {
delete[]this->str;
if (other.str != nullptr) {
size_t len = strlen(other.str) + 1;
str = new char[len];
strncpy(str, other.str, len );
}
}
return *this;
}
MyString& operator=(MyString&& other) {
if (this != &other) {
delete[]this->str;
str = other.str;
other.str = nullptr;
}
return *this;
}
bool operator==(const MyString& other) const {
return (strcmp(str, other.str) == 0);
}
bool operator!=(const MyString& other) const {
return !(*this == other);
}
char& operator[](size_t index) {
return str[index];
}
friend std::ostream& operator<<(std::ostream& os, const MyString& myStr);
};
std::ostream& operator<<(std::ostream& os, const MyString& myStr) {