# Include <cstdlib> # include <string. h ># include <iostream> using namespace std; class String {public: String (const char * str = NULL); // common const String (const String & other ); // copy the constructor ~ String (); // analysis function String & operator = (const String & other); friend ostream & operator <(ostream & OS, const String & s); private: char * data; // used to save the data String}; ostream & operator <(ostream & OS, const String & s) {int len = strlen (s. data); for (int I = 0; I <len; I ++) {OS <s. data [I];} return OS;} String: String (const char * str) {if (str = NULL) {data = new char [1]; if (data! = NULL) data = '\ 0';} else {int len = strlen (str); data = new char [len + 1]; if (data! = NULL) strcpy (data, str) ;}} String: String (const String & other) {int len = strlen (other. data); data = new char [len + 1]; if (data! = NULL) strcpy (data, other. data);} String ::~ String () {delete [] data;} String & String: operator = (const String & other) {if (this = & other) return * this; delete [] data; data = NULL; int len = strlen (other. data); data = new char [len + 1]; if (data! = NULL) strcpy (data, other. data); return * this ;} ######################################## ######################################## ######## int main (void) {String s1 ("string"); String s2 (s1); cout <"s1:" <s1 <endl; cout <"s2: "<s2 <endl; return 0 ;}
This article is from the "to simplicity" blog, please be sure to keep this source http://zhijian.blog.51cto.com/2057586/1268995