標籤:
CString類的定義如下:
class CMyString{public: CMyString(const char* pData=NULL); CMyString(const CMyString& str); CMyString& operator=(const CMyString& str); char* getData(){return this->m_pdata;}; ~CMyString(void);private: char *m_pdata;};
1、實現其建構函式
通用建構函式
複製建構函式
有兩種方式,一種是淺拷貝,一種是深拷貝,淺拷貝就是指向已經存在的記憶體位址,深拷貝就是分配新空間,將資料複製過來。
淺拷貝代碼:
// shallow copyCMyString::CMyString(char* pData){ m_pdata=pData;}CMyString::CMyString(const CMyString& str){ *this=str;}
深拷貝代碼:
CMyString::CMyString(const char* str){ if(str==NULL){ m_pdata=new char[1]; m_pdata[0]=‘\0‘; } else{ m_pdata=new char[strlen(str)+1]; strcpy(m_pdata,str); }}CMyString::CMyString(const CMyString &str){ m_pdata=new char[strlen(str.m_pdata)+1]; strcpy(m_pdata,str.m_pdata);}
2、解構函式
CMyString::~CMyString(){ delete[] m_pdata;}
3、賦值運算子函數
賦值運算子和複製建構函式的區別:
a. 複製建構函式產生新類對象,而賦值運算子不能,賦值運算子是用已存在的對象來建立另一個對象,給對象賦予一個新的值;
b. 由於複製建構函式是直接構造一個新的類對象,所以在初始化這個對象之前不用檢查來源物件是否和新對象相同。而賦值運算子需要這個操作,另外賦值運算子中如果原來的對象有記憶體配置,要先把記憶體釋放掉,避免記憶體泄露。
c. 當類中有指標類型的成員變數時,一定要重寫複製建構函式和賦值運算子函數,不能使用預設的。
CMyString& CMyString::operator=(const CMyString &str){ if(this==&str) return *this; delete []m_pdata; m_pdata=NULL; m_pdata=new char[strlen(str.m_pdata)+1]; strcpy(m_pdata,str.m_pdata); return *this;}
4、總的代碼
#include <iostream>#include <string.h>using namespace std;class CMyString{public: CMyString(const char* pData=NULL); CMyString(const CMyString& str); CMyString& operator=(const CMyString& str); char* getData(){return this->m_pdata;}; ~CMyString(void);private: char *m_pdata;};/*// shallow copyCMyString::CMyString(char* pData){ m_pdata=pData;}CMyString::CMyString(const CMyString& str){ *this=str;}*/// deep copyCMyString::CMyString(const char* str){ if(str==NULL){ m_pdata=new char[1]; m_pdata[0]=‘\0‘; } else{ m_pdata=new char[strlen(str)+1]; strcpy(m_pdata,str); }}CMyString::CMyString(const CMyString &str){ m_pdata=new char[strlen(str.m_pdata)+1]; strcpy(m_pdata,str.m_pdata);}CMyString::~CMyString(){ delete[] m_pdata;}CMyString& CMyString::operator=(const CMyString &str){ if(this==&str) return *this; delete []m_pdata; m_pdata=NULL; m_pdata=new char[strlen(str.m_pdata)+1]; strcpy(m_pdata,str.m_pdata); return *this;}int main(){ char a[]="hello"; CMyString str(a); CMyString str1(str); CMyString str2; CMyString str3; str3=str2=str; cout << str.getData()<< endl; cout << str1.getData()<< endl; cout << str2.getData()<< endl; cout << str3.getData()<< endl; return 0;}
(C++)已知String類的定義,實現其函數體