// Simple Array class to encapsulate a fixed length array // of integers that can be assigned and printed #ifndef _INTARRAY_H #define _INTARRAY_H #include #include using namespace std; class IntArray { public: IntArray(int size) : len(size) { try { data = new int[len]; } catch(const exception &) { throw OutOfSpace(len); } } IntArray(const IntArray & a) : len(a.len) { try { data = new int[len]; } catch(const exception &) { throw OutOfSpace(len); } for (int i = 0; i < len; ++i) data[i] = a.data[i]; } virtual ~IntArray() { delete [] data; } int length() const { return len; } // Array element access - lvalue and rvalue virtual int & operator [] (int i) { if (i < 0 || i >= len) throw OutOfBounds(i, len); else return data[i]; } virtual int operator [] (int i) const { if (i < 0 || i >= len) throw OutOfBounds(i, len); else return data[i]; } // Assignment (sizes need not match) IntArray & operator = (const IntArray & a) { if (this == &a) return *this; try { delete [] data; data = new int[len = a.len]; } catch(const exception &) { throw OutOfSpace(len); } for (int i = 0; i < len; ++i) data[i] = a.data[i]; return *this; } // Utility for printing virtual void print(ostream & o) const { o << "["; for (int i = 0; i < length(); ++i) o << (i == 0 ? "" : " ") << data[i]; o << "]"; } private: int *data; // The values in the array int len; // The size of the array public: // Exceptions class Error { public: Error(int n) : _size(n) { } virtual ~Error() { } virtual void print(ostream & o) const = 0; int size() const { return _size; } private: const int _size; }; class OutOfSpace : public Error { public: OutOfSpace(int n) : Error(n) { } void print(ostream & o) const { o << "IntArray out of space, size " << size(); } private: }; class OutOfBounds : public Error { public: OutOfBounds(int i, int n) : Error(n), _index(i) { } void print(ostream & o) const { o << "IntArray out of bounds access, index " << _index << ", size " << size(); } private: const int _index; }; }; inline ostream & operator << (ostream & o, const IntArray & a) { a.print(o); return o; } inline ostream & operator << (ostream & o, const IntArray::Error & e) { e.print(o); return o; } #endif