1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
#include "String.h"
#include <iostream>
#include <cstring>
using namespace std;
//Default constructor
String::String()
{
_strLen = 1;
_strPtr = new char[_strLen];
memcpy(_strPtr,"",_strLen);
}
//Constructor for C string literal
String::String(char* p)
{
_strLen = strlen(p)+1;
_strPtr = new char[_strLen];
memcpy(_strPtr,p,_strLen);
}
//Copy constructor
String::String(const String& Str)
{
_strLen = Str._strLen;
_strPtr = new char[_strLen];
memcpy(_strPtr,Str._strPtr,_strLen);
}
//Assignment operator =
String& String::operator = (const String& Str)
{
char* temp = new char[Str._strLen];
_strLen = Str._strLen;
memcpy(temp,Str._strPtr,_strLen);
delete[] _strPtr;
_strPtr = temp;
return *this;
}
//Global function
//Operator << (for cout << String commands)
ostream& operator << (ostream& os, const String& str)
{
short i;
for (i=0; i < str._strLen-1; i ++)
os << str._strPtr[i];
return os;
}
std::istream& operator >> (std::istream& is, String& Str)
{
const short BUFLEN = 256;
char Buf[BUFLEN];
memset(Buf,0,BUFLEN);
if(is.peek() == '\n')
is.ignore();
is.getline(Buf,BUFLEN,'\n');
Str = Buf; //Buf is a char*, so constructor String(char *) is called here, which creates a temporary string
//Then operator= is called to copy that string to Str
return is;
}
//Concatenate String + String
String String::operator+ (const String& Str)
{
//Str is b in a+b; "this" is a
String temp; //temp="", has called Default Constructor
strcpy(temp._strPtr, _strPtr);
temp._strLen = _strLen + Str._strLen-1;
strcat(temp._strPtr, Str._strPtr);
return temp;
}
//Destructor
String::~String()
{
delete []_strPtr;
}
|