拷貝構造函數要求把所有變量都需要做拷貝。在有繼承關系情況先,子類的拷貝構造函數,需要調用父類拷貝構造函數。示例代碼如下:
class Base{ public: virtual ~Base(); Base(const char *pStr); Base(const Base &other); virtual void CallFunction() ; public: char *m_pBase; }; Base::Base(const char *pStr){ if (pStr) { long iLen = strlen(pStr)+1; m_pBase = new char[iLen]; memset(m_pBase, 0, iLen); strcpy(m_pBase, pStr); }} Base::~Base(){ if (m_pBase) { delete [] m_pBase; m_pBase = NULL; } } Base::Base(const Base &other){ if (m_pBase) { delete m_pBase; m_pBase = NULL; } long iLen = strlen(other.m_pBase)+1; m_pBase = new char[iLen]; memset(m_pBase, 0, iLen); strcpy(m_pBase, other.m_pBase); }
class Child:public Base{ public: ~Child(); Child(const char *pStr , const char *pBase); Child(const Child &other); public: char *m_pChild; }; Child::Child(const char *pStr , const char *pBase):Base(pBase){//初始化列表中調父類構造函數 if (pStr) { long iLen = strlen(pStr)+1; m_pChild = new char[iLen]; memset(m_pChild, 0, iLen); strcpy(m_pChild, pStr); } } Child::Child(const Child &other):Base(other){//調父類拷貝構造函數 if (m_pChild) { delete m_pChild; m_pChild = NULL; } long iLen = strlen(other.m_pChild)+1; m_pChild = new char[iLen]; memset(m_pChild, 0, iLen); strcpy(m_pChild, other.m_pChild); } Child::~Child(){ if (m_pChild) { delete [] m_pChild; m_pChild = NULL; } }
Test:
Child ch("child", "base");
Child ch2(ch);