home *** CD-ROM | disk | FTP | other *** search
/ C Programming Starter Kit 2.0 / SamsPublishing-CProgrammingStarterKit-v2.0-Win31.iso / tybc4 / 14_1.cpp < prev    next >
C/C++ Source or Header  |  1994-05-26  |  2KB  |  82 lines

  1.  
  2.     #include <iostream.h>
  3.  
  4.  
  5.     const int True = 1;
  6.     const int False = 0;
  7.  
  8.  
  9.     template <class X> class ArrayType
  10.        {
  11.     protected:
  12.       int maxItems; // maximum number of items this will hold
  13.       int numItems; // number of items it is holding now
  14.       X  *items;    // array of items
  15.  
  16.     public:
  17.       ArrayType(int capacity);
  18.       ~ArrayType()       { delete [] items; }
  19.  
  20.       int InRange(int n) { return((n >= 0) && (n < numItems)); }
  21.       int Capacity()     { return maxItems; }
  22.       int AddItem(X& toAdd);
  23.       X& operator [] (int index) { return items[index]; }
  24.       }
  25.  
  26.  
  27.     template <class X> ArrayType<X>::ArrayType(int capacity)
  28.       {
  29.       maxItems = capacity;
  30.       items = new X[capacity];
  31.       numItems = 0;
  32.       } // end ArrayType::ArrayType()
  33.  
  34.  
  35.     template <class a> int ArrayType<a>::AddItem(a& toAdd)
  36.       {
  37.       if (numItems < maxItems)
  38.         {
  39.         items[numItems++] = toAdd;
  40.         return True;
  41.         }
  42.  
  43.       return False;
  44.       } // end ArrayType::AddItem()
  45.  
  46.  
  47.     template <class SomeType> size_t Size(const SomeType&)
  48.       {
  49.       return sizeof(SomeType);
  50.       } // end Size()
  51.  
  52.  
  53.     template <class D, class X> void Report(const char *s, D& d, X& x)
  54.       {
  55.       cout << endl << s << "has space for " << d.Capacity()
  56.            << " items.  Each item uses " << Size(x) << " bytes.\n";
  57.  
  58.       for (int i = 0; d.InRange(i); i++)
  59.         cout << "\t" << s << "[" << i << "] " << d[i] << endl;
  60.       } // end Report()
  61.  
  62.  
  63.     int main()
  64.       {
  65.       int               iVal;
  66.       float             fVal;
  67.       ArrayType <int>   iArray(3);
  68.       ArrayType <float> fArray(5);
  69.  
  70.       for (iVal = 0, fVal = 0.0; iVal < 10; ++iVal, fVal += 1.11)
  71.         {
  72.         iArray.AddItem(iVal);
  73.         fArray.AddItem(fVal);
  74.         }
  75.  
  76.       Report("iArray: ", iArray, iArray[0]);
  77.       Report("fArray: ", fArray, fArray[0]);
  78.  
  79.       return 0;
  80.       }
  81.  
  82.