A friend interview interview question, share to everybody, interviewer often ask, realize the four basic functions of String class will master.
A C + + class generally has at least four functions, that is, constructors, copy constructors, destructors, and assignment functions , and the general system defaults. But often the default is not what we expect, and we need to create them ourselves. They must understand their roles and meanings before they can be created, and they will be able to write effective functions.
#include <iostream> class CString {friend Std::ostream & operator<< (Std::ostream, CString &A
MP;);
Public://parameterless constructor CString ();
constructor with parameter CString (char *pstr);
Copy constructor CString (const CString &SSTR);
Destructors ~cstring ();
Assignment operators Overload CString & operator= (const CString & SSTR);
Private:char *m_pcontent;
};
Inline cstring::cstring () {printf ("null\n");
M_pcontent = NULL;
M_pcontent = new Char[1];
M_pcontent[0] = ' the ';
} inline cstring::cstring (char *pstr) {printf ("Use value contru\n");
M_pcontent = new Char[strlen (PSTR) + 1];
strcpy (M_pcontent, PSTR);
} inline cstring::cstring (const CString &sstr) {printf ("Use copy contru\n");
if (sstr.m_pcontent = null) M_pcontent = = NULL;
else {m_pcontent = new Char[strlen (sstr.m_pcontent) + 1];
strcpy (M_pcontent, sstr.m_pcontent); } inline Cstring::~cstring () {printf ("Use ~ \ n");
if (m_pcontent!= NULL) Delete [] m_pcontent;
} inline CString & cstring::operator = (const CString &sstr) {printf ("Use operator = \ n");
if (this = = &sstr) return *this;
Order is important in order to prevent the memory request from failing, m_pcontent is null char *ptempstr = new Char[strlen (sstr.m_pcontent) + 1];
delete [] m_pcontent;
M_pcontent = NULL;
M_pcontent = Ptempstr;
strcpy (M_pcontent, sstr.m_pcontent);
return *this;
} Std::ostream & operator<< (Std::ostream &os, CString & str) {os<<str.m_pcontent;
return OS; int main () {CString str3;//Call parameterless constructor CString str = "my cstring!";//declare string, equivalent to calling constructor STD::COUT<<STR&L
t;<std::endl; CString str2 = str;
Declaring a string is equivalent to calling a constructor std::cout<<str2<<std::endl; str2 = str;
Calling overloaded assignment operators std::cout<<str2<<std::endl;
return 0; }
Output:
Null
Use value Contru
My cstring!
Use copy Contru
My cstring!
Use operator =
My cstring!
Use ~
Use ~
Use ~
The above is a small set up to you introduced from the implementation of the string to see the C + + class of the four functions (common interview) all the narration, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!