1#include <iostream>2#include <cstring>3 4 classString5 {6 Public:7 String ();8String (Const Char*str);9String (ConstString &RHS);Ten~String (); One AString &operator=(ConstString &RHS); -Stringoperator+(ConstString &RHS); - Char operator[](ConstUnsignedintindex); the BOOL operator==(ConstString &RHS); -Friend Std::ostream &operator<< (Std::ostream & out,ConstString &RHS); - Private: - Char*m_data; + }; - + string::string () A { atStd::cout <<"default constructor"<<Std::endl; -M_data =New Char[1]; -m_data[0] =' /'; - } - -String::string (Const Char*str) in { -Std::cout <<"Non-default Constructor"<<Std::endl; to if(NULL = =str) + { -M_data =New Char[1]; them_data[0] =' /'; * } $ ElsePanax Notoginseng { -M_data =New Char[Strlen (str) +1]; the strcpy (m_data, str); + } A } the +String::string (ConstString &another) - { $Std::cout <<"copy Constructor"<<Std::endl; $M_data =New Char[Strlen (Another.m_data) +1]; - strcpy (m_data, another.m_data); - } the - BOOLString::operator==(ConstString &RHS)Wuyi { theStd::cout <<"bool = ="<<Std::endl; - intresult =strcmp (m_data, rhs.m_data); Wu if(0==result) - return true; About Else $ return false; - } - -String &string::operator=(ConstString &RHS) A { +Std::cout <<"Assign Constructor"<<Std::endl; the if( This= = &RHS) - return* This; $ delete []m_data; theM_data =New Char[Strlen (Rhs.m_data) +1]; the strcpy (m_data, rhs.m_data); the return* This; the } - inString string::operator+(ConstString &RHS) the { theStd::cout <<"+"<<Std::endl; About String newstring; the if(NULL = =rhs.m_data) thenewstring = * This; the Else if(NULL = =m_data) +NewString =RHS; - Else the {BayiNewstring.m_data =New Char[Strlen (Rhs.m_data) +strlen (m_data) +1]; the strcpy (Newstring.m_data, m_data); the strcat (Newstring.m_data, rhs.m_data); - } - returnnewstring; the } the the CharString::operator[](ConstUnsignedintindex) the { -Std::cout <<"[]"<<Std::endl; the returnM_data[index]; the } the 94Std::ostream &operator<< (Std::ostream & out,ConstString &RHS) the { the out<<Rhs.m_data; the return out;98 } About -string::~String ()101 {102Std::cout <<"destructor"<<Std::endl;103 delete []m_data;104 } the 106 intMainvoid)107 {108 Const Char*p ="Hello, World";109String s ="Hello, World";//constructor Implicit conversion call non-default constructor theString S1 (p);//calling a non-default constructor111String s2 = S1;//calling a non-default constructor theString S3;//calling the default constructor113s3 = S1;//Call Assignment Constructor theString S4 = s3 + S1;//Call the + operator while calling the default constructor the BOOLFlag (S1 = = s2);//call = = operator theStd::cout << S <<Std::endl;117Std::cout << S1 <<Std::endl;118Std::cout << S2 <<Std::endl;119Std::cout << S3 <<Std::endl; -Std::cout << Flag <<Std::endl;121 Charresult = s3[1];//invoke [] operator122Std::cout << Result <<Std::endl;123Std::cout << S4 <<Std::endl;124 the return 0;126}
C + + implements the String class