This string class is a comprehensive application of operator overloading and previous knowledge, providing functionality such as value semantics, string read and write, check and unchecked access, stream I/O, and string concatenation.
Definition of the 1.String class
classstring{//Definition of type structSrep;//represents a string that can be shared by several identical valuesSrep *Rep; Public:classCref;//implementation of subscript operations, differential treatment of read and write operations classRange ();//exception thrown when range error//constructs, assigns, and destructorsString ();//x = "";String (Const Char*);//x = "abc";String (Conststring&);//x = other_string;string&operator=(Const Char*); String&operator=(Conststring&); ~String (); //access operator with check voidCheckintIConst{if(I <0|| Rep->sz < i)ThrowRange ();} CharReadintIConst{returnRep->s[i];} voidWriteintICharc) {Rep= rep->get_own_copy (); Rep->s[i] =C; } Crefoperator[](inti) {check (i); returnCref (* This, i); } Char operator[](intIConst{check (i); returnRep->S[i]; } intSize ()Const{returnRep->sz;} //Other string Operationsstring&operator+=(Conststring&); String&operator+=(Const Char*); Friend Ostream&operator<< (Ostream&,Conststring&); Friend IStream&operator>> (Ostream&, string&); FriendBOOL operator==(Conststring& x,Const Char*s) { returnstrcmp (x.rep->s, s) = =0; } friendBOOL operator==(Conststring& x,Conststring&y) { returnstrcmp (x.rep->s, y.rep->s) = =0; }}; Stringoperator+(ConstString&,Conststring&); Stringoperator+(ConstString&,Const Char*); Stringoperator+(Const Char*,Conststring&);
Class 2.Srep: Sharing a string class that implements the same value
structstring::srep{Char*s;//pointer to an element intSz//Number of characters intN//Reference CountSrep (intNszConst Char*p) {N=1; SZ=Nsz; S=New Char[Sz +1]; strcpy (S, p); } ~Srep () {delete S; } Srep* Get_own_copy () {//implements write-time replication. if(n = =1)return This; N--; return NewSrep (SZ, s); } voidAssignintNszConst Char*p) { if(SZ! =Nsz) {delete []s; SZ=Nsz; S=New Char[Sz +1]; } strcpy (S, p); }Private: Srep (Constsrep&); Srep&operator=(Constsrep&);};
3.String Replication Implementation
String::string () {//empty string is the default valueRep =NewSrep (0,"");} String::string (Conststring& x) {//copy Constructorx.rep->n++; Rep=X.rep;} String::~string () {// Destructors if(--n = =0) Delete rep;} String&operator=(Conststring& x) {//Copy Assignmentx.rep->n++; if(--n = =0) Delete rep; Rep=X.rep; return* This;} String::string (Const Char*s) {Rep=NewSrep (strlen (s), s);} String&operator=(Const Char*s) {//Copy Assignment if(Rep->n = =1) Rep-Assign (strlen (s), s); Else{Rep->n--; Rep=NewSrep (strlen (s), s); } return* This;}
4. CREF for reading and writing
class string::cref{ class String; &S; int i; int II): S (ss), I (ii) {}public: operatorCharconst return s.read (i);} void operator= (char c) {s.write (I, c);}};
The road to coding--re-learning C + + (6): A String class