很久之前參加過一次面試,記得當時面試官問過我一個很基礎的代碼題:實現string類的四大基本函數!
一個C++類一般至少有四大函數,即構造函數、拷貝構造函數、析構函數和賦值函數,一般系統都會默認。但是往往系統默認的並不是我們所期望的,為此我們就有必要自己創造他們。在創造之前必須了解他們的作用和意義,做到有的放矢才能寫出有效的函數。
1 #include <iostream> 2 3 class CString 4 { 5 friend std::ostream & operator<<(std::ostream &, CString &); 6 public: 7 // 無參數的構造函數 8 CString(); 9 // 帶參數的構造函數 10 CString(char *pStr); 11 // 拷貝構造函數 12 CString(const CString &sStr); 13 // 析構函數 14 ~CString(); 15 // 賦值運算符重載 16 CString & operator=(const CString & sStr); 17 18 private: 19 char *m_pContent; 20 21 }; 22 23 inline CString::CString() 24 { 25 printf("NULL\n"); 26 m_pContent = NULL; 27 m_pContent = new char[1]; 28 m_pContent[0] = '\0'; 29 } 30 31 inline CString::CString(char *pStr) 32 { 33 printf("use value Contru\n"); 34 m_pContent = new char[strlen(pStr) + 1]; 35 strcpy(m_pContent, pStr); 36 } 37 38 inline CString::CString(const CString &sStr) 39 { 40 printf("use copy Contru\n"); 41 if(sStr.m_pContent == NULL) 42 m_pContent == NULL; 43 else 44 { 45 m_pContent = new char[strlen(sStr.m_pContent) + 1]; 46 strcpy(m_pContent, sStr.m_pContent); 47 } 48 } 49 50 inline CString::~CString() 51 { 52 printf("use ~ \n"); 53 if(m_pContent != NULL) 54 delete [] m_pContent; 55 } 56 57 inline CString & CString::operator = (const CString &sStr) 58 { 59 printf("use operator = \n"); 60 if(this == &sStr) 61 return *this; 62 // 順序很重要,為了防止內存申請失敗後,m_pContent為NULL 63 char *pTempStr = new char[strlen(sStr.m_pContent) + 1]; 64 delete [] m_pContent; 65 m_pContent = NULL; 66 m_pContent = pTempStr; 67 strcpy(m_pContent, sStr.m_pContent); 68 return *this; 69 } 70 71 std::ostream & operator<<(std::ostream &os, CString & str) 72 { 73 os<<str.m_pContent; 74 return os; 75 } 76 77 78 int main() 79 { 80 CString str3; // 調用無參數的構造函數 81 CString str = "My CString!"; // 聲明字符串,相當於調用構造函數 82 std::cout<<str<<std::endl; 83 CString str2 = str; // 聲明字符串,相當於調用構造函數 84 std::cout<<str2<<std::endl; 85 str2 = str; // 調用重載的賦值運算符 86 std::cout<<str2<<std::endl; 87 return 0; 88 }
輸出:
NULL
use value Contru
My CString!
use copy Contru
My CString!
use operator =
My CString!
use ~
use ~
use ~