1#include <cstdlib>2#include <cstring>3 4 classMystring5 {6 Public:7Mystring (Const Char*pdata)8 {9 if(pdata==NULL)Ten { Onedata =New Char[1]; A*data =' /'; - } - Else the { - intLen =strlen (pdata); -data =New Char[len+1]; - strcpy (data,pdata); + } - } +Mystring (ConstMystring &str) A { at intLen =strlen (str.data); -data =New Char[len+1]; - strcpy (data,str.data); - } - -Mystring &operator=(ConstMystring &str) in { - if( This!=&str) to { + Mystring strtemp (str); - Char*ptemp =Strtemp.data; theStrtemp.data = This-data; * This->data =ptemp; $ }Panax Notoginseng return This; - } theOstream &operator<< (Ostream &os,ConstMystring &str) + { Aos<<Str.data; the returnos; + } -Mystring &operator+(ConstMystring & str)Const $ { $ if(str.data!=NULL) - { - intLen1 =strlen (str.data); the intLen2 = strlen ( This-data); -Mystring strtemp (* ( This->data));//Create a temporary object to save the original object's dataWuyi Delete[]data;//Delete the original data theData=NULL; -data =New Char[len1+len2+2];//Opening and closing of new space Wustrcpy (Data,strtemp.data);//Copy -strcat (Data,str.data);//Stitching About } $ return This; - } - - Char operator[](intindex) A { + intLen =strlen (data); the if(index>len| | index<0) - { $Perror ("index is not in the cope!"); theExit0); the}Else the return*(( This->data) +index); the } - in~Mystring () the { the Delete[]data; About } the Private: the Char*data; the};
Implementation of the C + + string data type