Listing 2 This listing contains the declaration for a simple version of the String class, along with a simple test program.

#include <iostream.h>
#include <string.h>

class String
   {
   friend ostream &operator<<
      (ostream &os, const String &s);
public:
   String(const char *s);
   ~String() { delete [] str; }
   size_t length() { return len; }
   String &operator+=(char c);
private:
   size_t len,
   char *str;
   };

String::String(const char *s)
   {
   len = strlen(s);
   str = new char[len + 1];
   strcpy(str, s);
   }

String &String::operator+=(char c)
   {
   char *p = strcpy(new char[len + 2], str);
   p[len++] = c;
   p[len] = '\0';
   delete str;
   str = p;
   return *this;
   }

ostream &operator<<(ostream &os, const String &s)
   {
   return os << s.str;
   }

int main()
   {
   String s1("Hello");
   String s2 = s1;
   cout << "s1 = " << s1 << '\n';
   cout << "s2 = " << s2 << '\n';
   s1 += '!';
   cout << "s1 = " << s1 << '\n';
   cout << "s2 = " << s2 << '\n';
   return 0;
   }
// End of File