#include "iostream" #include "string.h" using namespace std; class Mystring{ private: char *str; public: Mystring(){}//无参构造函数 Mystring(const char *s)//有参构造函数 { str = new char[strlen(s)+1]; strcpy(str,s); } Mystring(const int num,const char s)//有参构造函数 { str = new char[num+1]; for(int i=0;i<num;i++) { str[i] = s; } str[num] = '\0'; } Mystring(const Mystring &s)//拷贝构造函数 { str = new char[strlen(s.str)+1]; strcpy(str,s.str); } Mystring(const char *s,const int num) { str = new char[num+1]; strncpy(str,s,num); str[num] = '\0'; } Mystring(const Mystring &s,const int index,const int len) { str = new char[len+1]; strncpy(str,s.str+index,len); str[len] = '\0'; } ~Mystring()//析构函数 { if(nullptr != str) { delete []str; str = nullptr; } } Mystring& operator=(const Mystring &s)//赋值运算符重载 { if(this != &s) { str = new char[strlen(s.str)+1]; strcpy(str,s.str); } return *this; } Mystring& operator+=(const Mystring &s)//加法运算符重载 { char *temp = new char[strlen(str)+strlen(s.str)+1]; strcpy(temp,str); strcat(temp,s.str); delete []str; str = temp; return *this; } Mystring& operator+=(const char *s)//加法运算符重载 { char *temp = new char[strlen(str)+strlen(s)+1]; strcpy(temp,str); strcat(temp,s); delete []str; str = temp; return *this; } //重载[] char &operator[](int index) { return str[index]; } //重载<> char* getstr() { return this->str; } void append(const char *s) { strcat(str,s); } void append(const char s) { str[strlen(str)] = s; str[strlen(str)+1] = '\0'; } int compare(const Mystring &s) { return strcmp(this->str,s.str); } int compare(const char *s) { return strcmp(this->str,s); } char at(int index) { if(index > strlen(str)-1) { cout<<"index out of range"<<endl; } return this->str[index]; } int length() { return strlen(str); } bool empty() { return strlen(str) == 0 ? 1 : 0; } }; int main() { Mystring s1("hello"); Mystring s2(5,'a'); Mystring s3(s1); Mystring s4; Mystring s5 = "sumu"; s4 = s1; s1 += s2; s1 += "world"; cout<<s1.getstr()<<endl; cout<<s2.getstr()<<endl; cout<<s3.getstr()<<endl; cout<<s4.getstr()<<endl; cout<<s5.getstr()<<endl; cout<<s5[1]<<endl; }
04-27
1554
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-29
6223
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-30
2382
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-30
2886
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)