class String{ private: char* str; public: String(): str(nullptr){} String(const char* s){ if(s){ str = new char[strlen(s) + 1]; strcpy(str, s); } else{ str = nullptr; } } String(const String& s){ if(s.str){ str = new char[strlen(s.str) + 1]; strcpy(str, s.str); } else{ str = nullptr; } } ~String(){ if(str){ delete[] str; } } String& operator=(const char* s){ if(str == s){ return *this; } if(str){ delete[] str; } if(s){ str = new char[strlen(s) + 1]; strcpy(str, s); } else{ str = nullptr; } return *this; } String& operator=(const String& s){ if(str == s.str){ return this; } if(str){ delete[] str; } if(s.str){ str = new char[strlen(s.str) + 1]; strcpy(str, s.str); } else{ str = nullptr; } return this; } String operator+(const char s){ String result; if(s){ result.str = new char[strlen(str) + strlen(s) + 1]; strcpy(result.str, str); strcat(result.str, s); } else{ result = this; } return result; } String operator+(const String& s){ String result; if(s.str){ result.str = new char[strlen(str) + strlen(s.str) + 1]; strcpy(result.str, str); strcat(result.str, s.str); } else{ result = this; } return result; } String& operator+=(const char s){ if(s){ char temp = new char[strlen(str) + strlen(s) + 1]; strcpy(temp, str); strcat(temp, s); if(str){ delete[] str; } str = temp; } return this; } String& operator+=(const String& s){ if(s.str){ char temp = new char[strlen(str) + strlen(s.str) + 1]; strcpy(temp, str); strcat(temp, s.str); if(str){ delete[] str; } str = temp; } return this; } char& operator[](int index){ return str[index]; } bool operator==(const char s){ if(!s){ return false; } return strcmp(str, s) == 0; } bool operator==(const String& s){ return strcmp(str, s.str) == 0; } bool operator<(const char s){ if(!s){ return false; } return strcmp(str, s) < 0; } bool operator<(const String& s){ return strcmp(str, s.str) < 0; } friend ostream& operator<<(ostream& os, const String& s){ os << s.str; return os; } friend istream& operator>>(istream& is, String& s){ char temp[4096]; is >> temp; s = temp; return is; } }

3、仿照标准字符串类string设计一个自己的字符串类String 主要完成以下任务1数据成员是字符指针可自动适应不同的串长度。2串复制既可使用字符串常量进行复制也可以使用其他的字符串对象进行复制。3串赋值。既可赋值为字符串常量也可以赋值为使用其他的字符串对象。4串连接。重载+和+=。5重载下标运算符 。6串比较。重载==和。7字符串输入和输出。重载和。

原文地址: https://www.cveoy.top/t/topic/gWoZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录