1 class CMyString 2 { 3 public: 4 CMyString(char *pData=NULL);//構造函數 5 CMyString(const CMyString& str);//拷貝構造函數 6 ~CMyString();//析構函數 7 private: 8 char* m_pData;//數據域,字符指針 9 };
關注如下幾點:是否把返回值類型聲明為該類型的引用,並在函數結束前返回實例的自身引用。是否把傳入的參數的類型聲明為常量引用。是否釋放實例自身的內存。是否判斷傳入的參數和當前的實例是不是同一個實例。
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 else 25 { 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 }