Value assignment operator function, value assignment operator
Question: The following is a declaration of the type CMyString. Please add a value assignment operator function for this type.
1 class CMyString2 {3 public: 4 CMyString (char * pData = NULL); // constructor 5 CMyString (const CMyString & str); // copy constructor 6 ~ CMyString (); // destructor 7 private: 8 char * m_pData; // data field, character pointer 9 };
Pay attention to the following points: whether to declare the return value type as a reference of this type, and return the instance's own reference before the function ends. Whether to declare the input parameter type as a constant reference. Whether to release the memory of the instance. Determines whether the input parameter is the same as the current instance.
1 #include "stdafx.h" 2 #include<string> 3 class CMyString 4 { 5 public: 6 CMyString(char* pData = NULL); 7 CMyString(const CMyString& str); 8 ~CMyString(void); 9 10 CMyString& operator = (const CMyString& str);11 12 void Print();13 private:14 char* m_pData;15 };16 17 CMyString::CMyString(char* pData)18 {19 if(pData == NULL)20 {21 m_pData = new char[1];22 m_pData[0] = '\0';23 }24 else25 {26 int length = strlen(pData);27 m_pData = new char[length + 1];28 strcpy(m_pData, pData);29 }30 }31 32 CMyString::CMyString(const CMyString &str)33 {34 int length = strlen(str.m_pData);35 m_pData = new char[length + 1];36 strcpy(m_pData, str.m_pData);37 }38 39 CMyString::~CMyString()40 {41 delete[] m_pData;42 }43 44 CMyString& CMyString::operator = (const CMyString& str)45 {46 if(this == &str)47 return *this;48 49 delete []m_pData;50 m_pData = NULL;51 52 m_pData = new char[strlen(str.m_pData) + 1];53 strcpy(m_pData, str.m_pData);54 55 return *this;56 }57 58 void CMyString::Print()59 {60 printf("%s\n", m_pData);61 }62 63 int main()64 {65 char* text = "Hello world";66 CMyString str1(text);67 CMyString str2;68 str2 = str1;69 70 printf("The expected result is: %s.\n", text);71 72 printf("The actual result is: ");73 str2.Print();74 75 return 0;76 }