A self-implemented string class, including basic constructor, copy constructor, assignment and destructor, comparison function, and input/output function.
# Include <iostream> # include <cstring> # include <iomanip> using namespace STD; Class mystring {public: mystring (const char * s = NULL ); mystring (const mystring & RHs); mystring & operator = (const char * s );~ Mystring (); char & operator [] (int I); int length () const {return Len;} Char * c_str () {return data ;} friend bool operator <(const mystring & ST1, const mystring & st2); friend bool operator> (const mystring & ST1, const mystring & st2 ); friend bool operator = (const mystring & ST1, const mystring & st2); friend mystring operator + (const mystring & S1, const mystring & S2 ); friend ostream & operator <(ostream & OS, Const mystring & St); friend istream & operator> (istream & is, mystring & St); Private: char * data; int Len ;}; mystring :: mystring (const char * s) {If (null = s) {Len = 0; Data = new char [1]; * Data = '\ 0 ';} else {Len = strlen (s); Data = new char [Len + 1]; strcpy (data, S) ;}} mystring: mystring (const mystring & RHs) {Len = strlen (RHS. data); Data = new char [Len + 1]; strcpy (data, RHS. data);} mystring & mystring: Operator = (const Mystring & RHs) {If (this = & RHs) return * This; Delete [] data; Len = strlen (RHS. data); Data = new char [Len + 1]; strcpy (data, RHS. data); return * This;} mystring & mystring: Operator = (const char * s) {Delete [] data; Len = strlen (s ); data = new char [Len + 1]; strcpy (data, S); return * This;} mystring ::~ Mystring () {Delete [] data;} Char & mystring: operator [] (int I) {return data [I] ;}// do not use friend when defining a friend function, and do not use string: bool operator <(const mystring & ST1, const mystring & st2) {return (strcmp (st1.data, st2.data) <0 );} bool operator> (const mystring & ST1, const mystring & st2) {return (strcmp (st1.data, st2.data)> 0);} bool operator = (const mystring & ST1, const mystring & st2) {return (strcmp (st1.data, st2.data) = 0);} mystring operator + (const mystring & ST1, const mystring & st2) {mystring res; Res. len = st1.len + st2.len; Res. data = new char [res. len + 1]; strcpy (res. data, st1.data); strcat (res. data, st2.data); Return res;} istream & operator> (istream & Cin, mystring & Str) {const int limit_string_size = 4096; Str. data = new char [limit_string_size]; CIN> SETW (limit_string_size)> Str. data; Str. len = strlen (Str. data); Return CIN;} ostream & operator <(ostream & cout, mystring & Str) {cout <Str. c_str (); Return cout;} int main () {mystring S1 ("I am S1."); mystring S2 = "Hello, this is s2 ."; cout <S1 <Endl; cout <S2 <Endl; mystring S3 (S1); cout <S3 <Endl; S3 = S2; cout <S3 <Endl; S3 = "My name is:" + S1; cout <S3 <Endl; S3 = S1 + S2; cout <S3 <Endl; return 0 ;}
Self-implemented string class