1#include <iostream>2#include <cstring>3 using namespacestd;4 5 6 classCString {7 Private:8 Char*m_pdata;9 Public:TenCString (Const Char* ptr =nullptr) { One if(ptr = = nullptr) M_pdata =nullptr; AM_pdata =New Char[Strlen (PTR) +1]; - strcpy (M_pdata, PTR); - } theCString (Constcstring&a) { - if(A.m_pdata = = nullptr) This->m_pdata =nullptr; - This->m_pdata =New Char[Strlen (A.m_pdata) +1]; -strcpy This-m_pdata, a.m_pdata); + } - +CString (cstring&&a) { A This->m_pdata =A.m_pdata; atA.m_pdata =nullptr; - } - -~CString () { - if( This-m_pdata) { - Delete[] This-m_pdata; in } - } to +cstring&operator=(Constcstring&a) { - if( This= = &a) the return* This; * $ if( This-m_pdata)Panax Notoginseng Delete[] This-m_pdata; - This->m_pdata =New Char[Strlen (A.m_pdata) +1]; thestrcpy This-m_pdata, a.m_pdata); + return* This; A } the +CStringoperator+=(Constcstring&a) { - if(A.m_pdata = =nullptr) { $ return* This; $}Else if( This->m_pdata = =nullptr) { - returnA; -}Else { the Char* TMP = This-m_pdata; - This->m_pdata =New Char[Strlen ( This->m_pdata) +strlen (a.m_pdata)Wuyi+1]; thestrcpy This-m_pdata, TMP); -Strcat This-m_pdata, a.m_pdata); Wu Delete[] tmp; - return* This; About } $ } - -Friend CStringoperator+(Constcstring& A,Constcstring&b) { - Char* Res =New Char[Strlen (A.m_pdata) + strlen (b.m_pdata) +1]; A strcpy (res, a.m_pdata); + strcat (res, b.m_pdata); the CString CS (res); - Delete[] Res; $ returnCS; the } the theFriend ostream&operator<< (ostream& OS,Constcstring&a) { theOS <<A.m_pdata; - returnos; in } the }; the About intMain () { the theCString A ("ABC"); the CString B (a); +A =b; -A + =b; theCString C = A +b;BayiStd::cout << C <<Std::endl; theStd::cout << a <<Std::endl; the - return 0; -}
Interview: C++string class implementation