Download this source file


// String0.cpp - An example of a simple string class.
// This version shows simple member functions, overloaded
// member operator functions, a constructor, and simple
// exceptions.  (These are good uses of exceptions.)  Note
// the use of an enum to set a constant.  Also note the name
// String0 since "string" is already used in namespace std.
// (We could omit the "using" clause if we really wanted to
// name the class "string".)
//
// As an exersize, change the class to have a dynamic size that
// is set by in the constructors.  (You will need to add a copy
// constructor and destructor.)
//
// Written by Wayne Pollock, Tampa Florida USA, 2000

#include <iostream>
#include <cstring>

using namespace std;

class string0
{
 public:
   string0 () { rep[0] = '\0'; }
   char& operator[] ( const int i ) const throw ( int );
   int operator== ( const string0 &s ) const;
   void set ( const char* const s ) throw ( char* );

 private:
   enum { MaxLength = 25 };  // 255 would be a more reasonable limit!
   char rep[MaxLength + 1];
};

int main ()  // This main is just a test driver for class string!
{  try
   {  string0 name1, name2;
      char s1[50], s2[50];

      cout << "Enter two names separated by a space: ";
      cin >> s1 >> s2;
      name1.set( s1 );
      name2.set( s2 );
      if ( name1 == name2 )
      {  cout << "The names are the same." << endl;
         name1[0] = 'X';
         cout << "Changed name1[0] = " << name1[0] << "." << endl;
      } else {
         cout << "The name are different." << endl;
         name1[60] = 'X';  // This should throw an exception!
         cout << "Changed name1[60] = " << name1[60] << "." << endl;
      }
      return 0;
   }
   catch ( char* msg )
   {  cerr << "*** Exception caught:  String too long:" << endl;
      cerr << "\t" << msg << endl;
      return -1;
   }
   catch ( int i )
   {  cerr << "*** Exception caught: index out of bounds ("
           << i << ")." << endl;
      return -1;
   }
   catch ( ... )
   {  cerr << "\n*** Unknown exception occured!\a" << endl;
      return -1;
   }
}

// String0 Class Implementation:

char& string0::operator[] ( const int i ) const throw ( int )
{  if ( i < 0 || i > MaxLength )
      throw i;
   return char( rep[i] );
}

int string0::operator== ( const string0 &s ) const
{   return ( ! strcmp( rep, s.rep ) );
}

void string0::set ( const char* const s ) throw ( char* )
{  if ( strlen(s) > MaxLength )
      throw (char*) s;
   strcpy( rep, s );
   return;
}