// // demonstrates a basic array class // // Written by Maxwell Sayles, 2001, for CPSC331, University of Calgary. // #include #include #include using namespace std; // // simple array class that handles integers // class Array { public: Array (int low, int high); // indexes low through high inclusive ~Array(); int getLow() { return this->low; } int getHigh() { return this->high; } int getElementCount() { return this->high - this->low + 1; } int getElement (int index); void setElement (int index, int value); // provide operator overloading, more complicated syntactically int& operator[] (int index); private: int* data; int low; int high; }; // // creation // Array::Array (int low, int high) { this->low = low; this->high = high; this->data = new int[high-low+1]; } // // destruction // Array::~Array() { delete[] this->data; } // // retrieve an element at the specified index // int Array::getElement (int index) { return this->data[index - this->low]; } // // set the elements at the specified index // void Array::setElement (int index, int value) { this->data[index - this->low] = value; } // // C-Style array indexing // int& Array::operator[] (int index) { return this->data[index - this->low]; } // // program entry // int main() { int i = 0; // seed the random number generator srand((unsigned int)time(0)); // ask user for upper and lower bounds of the array int low = 0; int high = 0; cout << "Enter array low bound (e.g. 0) : " << flush; cin >> low; cout << "Enter array upper bound (e.g. 100) : " << flush; cin >> high; cout << endl; // construct the array Array a(low, high); // this portion demonstrates the getter and setter methods cout << "Testing getter/setter methods..." << endl; // store elements into array for (i = a.getLow(); i <= a.getHigh(); i ++) { a.setElement (i, rand() % a.getElementCount()); } // get elements out of array for (i = a.getLow(); i <= a.getHigh(); i ++) { cout << a.getElement (i) << ' '; } cout << endl << endl; // this portion demonstrates C-Style array indexing cout << "Testing operator overloading..." << endl; // use operator overloading, store elements into array for (i = a.getLow(); i <= a.getHigh(); i ++) { a[i] = rand() % a.getElementCount(); } // use operator overloading, get elements out of array for (i = a.getLow(); i <= a.getHigh(); i ++) { cout << a[i] << ' '; } cout << endl; }