标签:
很久之前参加过一次面试,记得当时面试官问过我一个很基础的代码题:实现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 ~
标签:
原文地址:http://www.cnblogs.com/androidshouce/p/5582727.html