Code:
#include <iostream>
using namespace std;
class String
{
private:
friend int operator==(const String& lhs, const String& rhs);
friend ostream& operator<<(ostream& os, String& s);
public:
String& operator=(const String&);
String& operator+=(const String&);
public:
~String ();
String(const char* = "");
String(const String&);
private:
char *m_pChars;
};
//Acts like a conversion operator: 'c-style char' to 'String'
String::String(const char *s)
{
// need to copy the given string. If s is zero, make a null string!
if (s)
{
int len = strlen(s) + 1;
m_pChars = new char[len];
strcpy(m_pChars, s);
}
else
{
m_pChars = new char[1];
*m_pChars = '\0';
}
}
String::String(const String& s)
{
m_pChars = new char[strlen(s.m_pChars) + 1];
strcpy(m_pChars, s.m_pChars);
}
String::~String() { delete[] m_pChars; }
String& String::operator=(const String& s)
{
if (this != &s)
{
delete[] m_pChars; // first delete old
int len = strlen(s.m_pChars) + 1;
m_pChars = new char[len];
strcpy(m_pChars, s.m_pChars);
}
return *this;
}
//MUST be defined outside class; So don't forget to make it a friend in the class that uses it.
ostream& operator<<(ostream& os, String& s)
{
os<<s.m_pChars;
return os; //Always return inserter/extractor.
}
int operator==(const String& lhs, const String& rhs)
{
return (strcmp(lhs.m_pChars,rhs.m_pChars) == 0);
}
String& String::operator+=(const String& s)
{
char* buffer = new char[strlen(m_pChars) + strlen(s.m_pChars) + 1];
strcpy(buffer, m_pChars);
strcat(buffer, s.m_pChars);
delete[] m_pChars;
m_pChars = buffer;
return *this;
}
String operator+(const String& lhs, const String& rhs)
{
String buffer(lhs); // calls copy ctor
buffer += rhs; // calls our overloaded +=
return buffer;
}
int main()
{
String A("Hello! ");
A=A; //Test for self-assignment.
String B="How are you?";
cout<<("Hello! " == A)<<endl; //Hey... what's this? It works :)
A+=B;
cout<<A<<endl;
return 0;
}