The implementation of a string class must be sketched out quickly.
1 classString2 {3 Public:4String (Const Char*STR = NULL);//Common Constructors5String (ConstString &other);//copy Constructor6~ String (void);// Destructors7String &operator=(ConstString &other);//Assignment Function8 Private:9 Char*m_data;//used to save stringsTen }; One A //Common Constructors -String::string (Const Char*str) - { the if(str==NULL) - { -M_data =New Char[1];//automatic application of an empty string to the closing flag '//Add points: null judgment on M_data -*m_data =' /'; +}Else{ - intLength =strlen (str); +M_data =New Char[length+1];//Better if you can add a NULL judgment A strcpy (m_data, str); at } - } - - //destructor for string -String::~string (void) - { inDelete[] m_data;//or delete m_data; - } to + //copy Constructor -String::string (ConstString &other)//input parameter is const type the { * intLength =strlen (other.m_data); $M_data =New Char[length+1];//null judgment for M_dataPanax Notoginseng strcpy (m_data, other.m_data); - } the +String & string::operator=(ConstString &other)//input parameter is const A type the { + if( This! = &other)//Check self-assigned value - { $ String strtemp (str); $ Char* Ptemp =Strtemp.m_pdata; -Strtemp.m_pdata =m_pdata; -M_pdata =ptemp; the } - return* This;//returns a reference to this objectWuyi}
View Code
1 //assignment function, poor practice2String & string::operator=(ConstString &other)//input parameter is const3 type4 {5 if( This= = &other)//Check self-assigned value6 return* This;7Delete[] m_data;//freeing up legacy memory resources8 intLength =strlen (other.m_data);9M_data =New Char[length+1];//null judgment for M_dataTen strcpy (m_data, other.m_data); One return* This;//returns a reference to this object A}
View Code
"C + + FAQ"-Write a string implementation