home *** CD-ROM | disk | FTP | other *** search
/ C by Discovery (4th Edition) / C_By_Discovery_4th_Edition.tar / C_By_Discovery_4th_Edition / _DISK_ / ch12 / array.h < prev    next >
C/C++ Source or Header  |  2005-06-16  |  2KB  |  74 lines

  1. //                      array.h
  2. //
  3. // Contains the declaration and implementation
  4. // of a template array class.
  5.  
  6. // Include Files
  7. #include <stdlib.h>
  8.  
  9. template< class T, int n >                                // Note 1
  10. class Array
  11. {
  12. public:
  13.     Array();
  14.     // PRECONDITION:  none.
  15.     //
  16.     // POSTCONDITION: the array has been initialized 
  17.     //                with all bits set to 0.
  18.  
  19.     Array( const Array<T,n>& A );                         // Note 2
  20.     // PRECONDITION:  none.
  21.     //
  22.     // POSTCONDITION: the newly created array is a copy of A.
  23.  
  24.     bool operator == ( Array<T,n>& A ) const;             // Note 2
  25.     // PRECONDITION:  none.
  26.     //
  27.     // POSTCONDITION: Returns true if the two arrays 
  28.     //                have identical elements and false, if not.
  29.  
  30.     T& operator[]( int index );
  31.     // PRECONDITION:  index mst be greater than or equal 
  32.     //                to 0 and less than n.
  33.     // POSTCONDITION: The element at position index in 
  34.     //                the array is returned.
  35.  
  36. private:
  37.     T elts[ n ];
  38. };
  39.  
  40. template< class T, int n >                                // Note 1
  41. Array<T,n>::Array()                                       // Note 3
  42. {
  43.     for ( int i = 0; i < n; i++ )
  44.         elts[i] = T();
  45. }
  46.  
  47. template< class T, int n >                                // Note 1
  48. Array<T,n>::Array( const Array<T,n>& A )             // Notes 2 & 3
  49. {
  50.     for ( int i = 0; i < n; i++ )
  51.         elts[i] = A.elts[i];
  52. }
  53. template< class T, int n >                                // Note 1
  54. bool Array<T,n>::operator== ( Array<T,n>& A ) const  // Notes 2 & 3
  55. {
  56.     bool match = true;
  57.  
  58.     for ( int i = 0; i < n; i++ )
  59.         if ( elts[i] != A.elts[i] )
  60.             match = false;
  61.     return match;
  62. }
  63.  
  64. template< class T, int n >                                // Note 1
  65. T& Array<T,n>::operator[]( int index )                    // Note 3
  66. {
  67.     if ( index < 0 || index >= n ) {
  68.         cerr << "Index out of range\n";                      // Note 4
  69.         exit( 1 );
  70.     }
  71.     return elts[ index ];
  72. }
  73.  
  74.