写string类遇到的问题
程序代码:
// wjbString.cpp: implementation of the CwjbString class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "wjbString.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CwjbString::CwjbString() { m_nLength = 0; m_pString = NULL; } CwjbString::CwjbString(char * pString) { if(NULL != pString) { m_nLength = Strlen(pString); m_pString = new char[m_nLength + 1]; Strcpy(m_pString, pString); } } CwjbString::CwjbString(CwjbString &r) { m_nLength = r.m_nLength; m_pString = new char[m_nLength + 1]; Strcpy(m_pString, r.m_pString); } CwjbString::~CwjbString() { if(NULL != m_pString) { delete [] m_pString; m_pString = NULL; } } void CwjbString::SetString(const char *pString) { delete [] m_pString; m_pString = NULL; m_nLength = Strlen(pString); m_pString = new char[m_nLength + 1]; Strcpy(m_pString, pString); } char * CwjbString::GetString() { return m_pString; } int CwjbString::GetLength() { return m_nLength; } int CwjbString::Strlen(const char *pString) { int nLength = 0; while('\0' != *pString++) { nLength++; } return nLength; } char * CwjbString::Strcpy(char *pString, const char *pString1) { for(int i = 0; i <= Strlen(pString1); i++) { pString[i] = pString1[i]; } return pString; } char * CwjbString::Strcat(char *pString, const char *pString1) { char *pTemp = pString; while('\0' != *pTemp++) continue; while('\0' != (*pTemp++ = *pString1++)) continue; return pString; } CwjbString& CwjbString::StrLink(const char *pString, const char *pString1) { int n1 = Strlen(pString); int n2 = Strlen(pString1); m_pString = new char[n1+n2+1]; int i; for(i = 0; i < n1; i++) { m_pString[i] = pString[i]; } for(int j = 0; j <= n2; j++) { m_pString[i+j] = pString1[j]; } m_nLength = n1 + n2; return *this; } CwjbString& CwjbString::operator = (const CwjbString& a) { m_nLength = a.m_nLength; m_pString = new char[m_nLength + 1]; Strcpy(m_pString, a.m_pString); return *this; } CwjbString& CwjbString::operator = (const char *pString) { m_nLength = Strlen(pString); m_pString = new char[m_nLength + 1]; Strcpy(m_pString, pString); return *this; } CwjbString CwjbString::operator + (const CwjbString& a) { CwjbString Temp; Temp = Temp.StrLink(m_pString, a.m_pString); return Temp; } CwjbString CwjbString::operator + (const char *pString) { CwjbString Temp; Temp = StrLink(m_pString, pString); return Temp; } CwjbString operator + (const char *pString , const CwjbString& a) { CwjbString Temp; Temp = Temp.StrLink(pString, a.m_pString); return Temp; }1.主要问题:那个StrLink出了问题,该怎么纠正,自己反复变化,就是改不好。大家帮我纠正下!2.附加问题:(一直困惑着我,无法解决)strcat,就是字符连接,a += b;
那么a的内存大小需要改变,那么这个重新动态内存是由strcat重新分配,还是由外部处理。听说外部处理是一开始就给a分配多余够用的空间。可现在在写string类里,分配的空间是刚好够用的。如果是由strcat函数内部处理,那么这个动态内存,怎么释放掉,因为要返回动态内存分配的这个指针。