#include "CStr.hpp" #include "spitball.hpp" #include #include CStr::CStr() { // default constructor pData = new char[1]; if (pData==NULL) throw spitball("Failure to allocate CStr in CStr::CStr()",-1); *pData = '\0'; nLength = 0; } CStr::CStr(char *s) { //typecasting constructor pData = new char[strlen(s)+1]; if (pData==NULL) throw spitball("Failure to allocate CStr in CStr::CStr(char *)",-1); strcpy(pData, s); nLength = strlen(s); } CStr::CStr(const CStr &str) { // copy constructor char *s = str.get(); int n = str.getlength(); pData = new char[n+1]; if (pData==NULL) throw spitball("Failure to allocate CStr in CStr::CStr(CStr)",-1); strcpy(pData, s); nLength = n; } CStr::~CStr() { delete [] pData; } void CStr::cpy(char *s) { //Copy string arg to object int n = strlen(s); if (nLength != n) { if (pData) delete [] pData; pData = new char[n+1]; if (pData==NULL) throw spitball("Failure to allocate CStr in CStr::cpy",-1); nLength = n; } strcpy(pData, s); } void CStr::cat(char *s) { //Concatenate string arg int n; char *pTemp; n = strlen(s); if (n==0) return; pTemp = new char[n + nLength + 1]; if (pTemp==NULL) throw spitball("Failure to allocate CStr in CStr::cat",-1); else { if (pData) { strcpy(pTemp, pData); delete [] pData; } } strcat(pTemp, s); pData = pTemp; nLength += n; } CStr operator+(CStr str1, CStr str2) { CStr new_string(str1); new_string.cat(str2.get()); return new_string; } /**** not needed because of CStr::CStr(Char *) CStr operator+(CStr str, char *s) { CStr new_string(str); new_string.cat(s); return new_string; } CStr operator+(char *s, CStr str) { CStr new_string(s); new_string.cat(str.get()); return new_string; } */