用C++实现了简易版字符串类,原理还是用C语言风格的字符指针实现,主要为了练习C++的内存管理。
String有功能构造析构复制赋值和常见操作符,特别需要注意的是赋值和+=的时候相当于把原理的String的字符串抛弃掉了,这时候如果不对之前的字符串进行释放处理的话会造成内存泄漏!!
1 #include<bits/stdc++.h> 2 using namespace std; 3 4 class String { 5 private: 6 char *ptr; //字符串首指针 7 size_t len; //字符串长度 8 9 public: 10 String(const char *str=NULL); //构造函数 11 String(const String &str); //复制构造函数 12 ~String(); //析构函数 13 14 friend String operator + (const String& str1,const String& str2); //重载加号 15 16 String& operator = (const String& str); //重载赋值运算符 17 String& operator += (const String& str); //重载+= 18 bool operator == (const String &str); //重载相等判断符 19 char& operator [] (int n); //重载下标取值 20 21 bool operator != (const String& str) const; 22 bool operator < (const String& str) const; 23 bool operator <= (const String& str) const; 24 bool operator > (const String& str) const; 25 bool operator >= (const String& str) const; 26 27 size_t size() const; //返回长度 28 const char* c_str() const; //获得String的C风格字符串 29 30 //输入输出运算 31 friend istream& operator >> (istream &is,String &str); 32 friend ostream& operator << (ostream &os,String &str); 33 }; 34 35 //字符串拷贝函数:把strSrc串拷贝到strDest串 36 char* strcpy(char *strDest,const char *strSrc) { 37 if (strDest==NULL || strSrc==NULL) return NULL; 38 if (strDest==strSrc) return strDest; 39 char *head=strDest; //先把首指针保存一份用来输出 40 while ((*strDest++ = *strSrc++) != '