A long time ago to attend an interview, I remember the interviewer asked me a very basic code problem: the implementation of the four basic functions of the String Class!
A C + + class generally has at least four functions, that is, constructors, copy constructors, destructors, and assignment functions, the general system will default. But often the system defaults are not what we expect, so we need to create them ourselves. It is important to understand their roles and meanings before they are created and to write effective functions in a targeted way.
1#include <iostream>2 3 classCString4 {5Friend Std::ostream &operator<< (Std::ostream &, CString &);6 Public:7 //constructor with no parameters8 CString ();9 //Constructors with parametersTenCString (Char*pStr); One //copy Constructor ACString (ConstCString &sStr); - // Destructors -~CString (); the //assignment operator Overloading -CString &operator=(ConstCString &sStr); - - Private: + Char*m_pcontent; - + }; A at inline cstring::cstring () - { -printf"null\n"); -M_pcontent =NULL; -M_pcontent =New Char[1]; -m_pcontent[0] =' /'; in } - toInline cstring::cstring (Char*pStr) + { -printf"Use value contru\n"); theM_pcontent =New Char[Strlen (PSTR) +1]; * strcpy (m_pcontent, pStr); $ }Panax Notoginseng -Inline cstring::cstring (ConstCString &sStr) the { +printf"Use copy contru\n"); A if(Sstr.m_pcontent = =NULL) theM_pcontent = =NULL; + Else - { $M_pcontent =New Char[Strlen (Sstr.m_pcontent) +1]; $ strcpy (m_pcontent, sstr.m_pcontent); - } - } the -Inline cstring::~CString ()Wuyi { theprintf"Use ~ \ n"); - if(M_pcontent! =NULL) Wu Delete [] m_pcontent; - } About $Inline CString & CString::operator= (ConstCString &sStr) - { -printf"Use operator = \ n"); - if( This= = &sStr) A return* This; + //order is important in order to prevent memory requests from failing, m_pcontent is null the Char*ptempstr =New Char[Strlen (Sstr.m_pcontent) +1]; - Delete [] m_pcontent; $M_pcontent =NULL; theM_pcontent =Ptempstr; the strcpy (m_pcontent, sstr.m_pcontent); the return* This; the } - inStd::ostream &operator<< (Std::ostream &os, CString &str) the { theos<<str.m_pcontent; About returnos; the } the the + intMain () - { theCString STR3;//calling a parameterless constructorBayiCString str ="My cstring!";//declares a string, which is equivalent to calling the constructor thestd::cout<<str<<Std::endl; theCString str2 = str;//declares a string, which is equivalent to calling the constructor -std::cout<<str2<<Std::endl; -str2 = str;//calling an overloaded assignment operator thestd::cout<<str2<<Std::endl; the return 0; the}
Output:
Null
Use value Contru
My cstring!
Use copy Contru
My cstring!
Use operator =
My cstring!
Use ~
Use ~
Use ~
A look at the four functions of C + + class from the implementation of string class