#include <iostream> #include <cstring> using namespace std; class CMyString { public: CMyString(char *m_pData=NULL); CMyString(const CMyString& str); ~CMyString(void); CMyString& operator=(const CMyString& str); void print(); private: char *m_pData; }; CMyString::CMyString(char *m_pData) { if(m_pData!=NULL) { this->m_pData = new char[strlen(m_pData)+1]; strcpy(this->m_pData, m_pData); }else{ this->m_pData = NULL; } } CMyString::CMyString(const CMyString& str) { new (this) CMyString(str.m_pData); //this->m_pData = new char[strlen(str.m_pData)+1]; //strcpy(this->m_pData, str.m_pData); } CMyString::~CMyString() { if(m_pData!=NULL) { delete [] m_pData; m_pData = NULL; } } CMyString& CMyString::operator=(const CMyString& str) { if(this!=&str) { CMyString strTemp(str); char * pTemp = strTemp.m_pData; strTemp.m_pData = m_pData; m_pData = pTemp; } return *this; } void CMyString::print() { if(m_pData!=NULL) cout<<m_pData<<endl; } int main() { CMyString str("I'm xxxx."); str.print(); CMyString cpy1 = str; cpy1.print(); CMyString cpy2 = "hello World"; cpy2.print(); CMyString cpy3; cpy3 = str; cpy3.print(); CMyString cpy4, cpy5; cpy4 = cpy5; cpy4.print(); CMyString cpy6(cpy5); return 0; }