Two class with pointer members (class String)
1. Test code (use effect)
int Main () { string S1 (), string s2 ("hello"); // constructor Function String S3 (S1); // Copy Construction cout << S3 << Endl; = S2; // Copy Assignment cout << S3 << Endl;}
2 Big Three (three kinds of special functions)
classstring{ Public: String (Const Char* CStr =0); String (Conststring& str);//arguments are references to objects of the same type, copy constructsstring&operator=(Conststring& str);//Copy Assignment~string ()// Destructors Char* GET_C_STR ()Const{ returnm_data; }Private: Char*m_data;};
2.1 ctor & Dtor (Construction and destruction)
inlinestring::string (Const Char* CStr =0){ if(CStr) {m_data=New Char[Strlen (CStr) +1]; strcpy (M_DATA,CSTR); } Else{//length not specifiedM_data =New Char[1]; *m_data =' /'; }}inlinestring::~String () {Delete[] m_data;}
2.2 Class with pointer must have copy ctor (copy construction) and copy op (copy assignment)
Deep copy and shallow copy
Deep copy:
inlinestring::string (const string& str) { newchar1] ; // direct access to the private data of another object // strcpy (m_data, str.m_data);}
Copy Assignment function:
Idea: If the right side is copied to the left, the steps are empty to the left, the same space is assigned to the right, and the copy is completed.
inlinestring& String::operator=(Conststring&str) { if( This= = &str) {//Detecting self-assignment is not just a matter of efficiency return* This;//if not tested, may cause undefined behavior, see explanation } Delete[] m_data;//Clear leftM_data =New Char[Strlen (Str.m_data) +1];//Open Spacestrcpy (M_data, str.m_data);//Complete Copy return* This}
Summary: A class with pointer variables, be sure to re-copy the construction, copy assignment and destructor!
C + + Object-oriented Programming note 2 (Class with pointer members)