this class template array. overloaded [ ]
operator in hopes fix "out of bounds" issue. print outs work well, except if falls out of range, compiler enables range default , displays 6 digit number.
perhaps looking better way initialize arrays appropriate element number better check , if fall out of range when looking element, display error.
// implement class myarray solves array index // "out of bounds" problem. #include <iostream> #include <string> #include <cmath> using namespace std; template <class t> class myarray { private: t* array; int begin; int end; int size; public: myarray(int); myarray(int, int); ~myarray() { }; void printresults(); // attempting overload [ ] operator find correct elements. int operator[] (int position) {if (position < 0) return array[position + abs(begin)]; else return array[position - begin]; } }; template <class t> myarray<t>::myarray(int newsize) { size = newsize; end = newsize-1; begin = 0; array = new t[size] {0}; } template <class t> myarray<t>::myarray(int newbegin, int newend) { begin = newbegin; end = newend; size = ((end - begin)+1); array = new t[size] {0}; } // used checking purposes. template <class t> void myarray<t>::printresults() { cout << "your array " << size << " elements long" << endl; cout << "it begins @ element " << begin << ", , ends @ element " << end << endl; cout << endl; } int main() { int begin; int end; myarray<int> list(5); myarray<int> mylist(2, 13); myarray<int> yourlist(-5, 9); list.printresults(); mylist.printresults(); yourlist.printresults(); cout << list[0] << endl; cout << mylist[2] << endl; cout << yourlist[9] << endl; return 0; }
first of all, operator[]
not correct. defined return int
. compile-time error instantiate array of something, not implicitly convertible int
.
it should rather be:
t& operator[] (int position) { //... }
and, of course:
const t& operator[] (int position) const { //you may want access arrays declared const, don't you? }
now:
i overloaded [ ] operator in hopes fix "out of bounds" issue.
you didn't fix anything. allowed clients of array define custom boundaries, nothing more. consider:
myarray<int> yourlist(-5, 9); yourlist[88] = 0;
does code check out-of-bounds
cases one? no.
you should it:
int operator[] (int position) { if((position < begin) || (position > end)) //invalid position throw std::out_of_range("invalid position!"); //ok, safely return desired element }
note, throwing exception best solution in such case. quote std::out_of_range
doc:
it standard exception can thrown programs. components of standard library, such
vector
,deque
,string
,bitset
throw exceptions of type signal arguments out of range.