C++ 自定义字符串类 String 实现详解:功能、代码与优化
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; } };
原文地址: https://www.cveoy.top/t/topic/oy4F 著作权归作者所有。请勿转载和采集!