Here are the files you will need, the name of the file is commented on top:
Code:
// myString.h: interface for the CmyString class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_MYSTRING_H__60C5F526_B091_4FE3_B074_23E7BF46A940__INCLUDED_)
#define AFX_MYSTRING_H__60C5F526_B091_4FE3_B074_23E7BF46A940__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CmyString
{
public:
CmyString& operator+=(const CmyString& b);
CmyString operator+(const CmyString& b);
CmyString& operator=(const CmyString& b);
CmyString(char* pstr ="Default String");
CmyString(const CmyString& temp);
virtual ~CmyString();
void printstr();
char* getString() const { return m_pstr; };
private:
int length;
char* m_pstr;
};
#endif // !defined(AFX_MYSTRING_H__60C5F526_B091_4FE3_B074_23E7BF46A940__INCLUDED_)
Code:
// myString.cpp: implementation of the CmyString class.
//
//////////////////////////////////////////////////////////////////////
#include "myString.h"
#include <iostream>
#include <cstring>
using namespace std;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CmyString::CmyString(char* pstr)
{
m_pstr = new char [strlen(pstr) + 1];
strcpy(m_pstr, pstr);
length = strlen(m_pstr);
}
CmyString::CmyString(const CmyString& temp)
{
m_pstr = new char [strlen(temp.m_pstr) + 1];
strcpy(m_pstr, temp.m_pstr);
}
CmyString::~CmyString()
{
delete [] m_pstr;
m_pstr = NULL;
}
void CmyString::printstr()
{
cout << m_pstr << endl;
}
CmyString& CmyString::operator=(const CmyString& b)
{
if(this != &b)
{
length= b.length;
delete [] m_pstr;
m_pstr = new char[strlen(b.m_pstr) + 1];
strcpy(m_pstr, b.m_pstr);
}
return *this;
}
CmyString CmyString::operator+(const CmyString& b)
{
CmyString temp;
temp.length = this->length + b.length;
delete [] temp.m_pstr;
temp.m_pstr = new char [temp.length + 1];
strcpy(temp.m_pstr, this->m_pstr);
strcat(temp.m_pstr, b.m_pstr);
return temp;
}
CmyString& CmyString::operator+=(const CmyString& b)
{
this->length += b.length;
char* tempString = new char [this->length + 1];
strcpy(tempString, this->m_pstr);
delete[] this->m_pstr;
this->m_pstr = new char [this->length + 1];
strcpy(this->m_pstr, tempString);
strcat(this->m_pstr, b.m_pstr);
return *this;
}
Code:
// string_main.CPP
// A sample string problem
#include <iostream>
#include "myString.h"
using namespace std;
int main()
{
CmyString a ("my first");
CmyString b ("your first");
CmyString c ("our first");
a.printstr();
b.printstr();
c.printstr();
CmyString d;
d = a+b+c;
d.printstr();
//c += a;
//c.printstr();
return 0;
}