powell@ole.UUCP (Gary Powell) (06/07/90)
Re: Overloading [] This double class object appears to do what I want but boy what a lot of code just to do 2 dimminsional arrays! I would gladly take any suggestions on how to reduce this mess. The basic idea here is have n class types so that each [] operation evaluates to the next dim. until an elemental item is reached. what I want is the ability to do the evaluation myself in one step instead. Ie overload [](int,int,....int) or [](int)[](int)....[](int). #include <stream.h> class INT_ROW { public: INT_ROW(int); int & operator[](int); ~INT_ROW(); private: int max_row, *array; }; INT_ROW::INT_ROW(int r) { int i; max_row = r; array = new int [r]; // initialize the data for (i = 0; i< max_row; i++) array[i] = 0; } INT_ROW::~INT_ROW() { delete array; max_row = 0; } int & INT_ROW::operator[](int r) { int *ptr; if (r >= max_row) { cout << "Array bounds exceeded.\n"; exit (1); } ptr = &array[r]; return *ptr; } class INT_ARRAY { public: INT_ARRAY(int,int); INT_ROW & operator[](int); ~INT_ARRAY(); private: int max_col; INT_ROW **array; }; INT_ARRAY::INT_ARRAY(int r, int c) { int i; max_col = c; array = new INT_ROW *[c]; for (i = 0; i< c; i++) { array[i] = new INT_ROW (r) ; } } INT_ARRAY::~INT_ARRAY() { int i; for (i = 0; i< max_col; i++) { delete array[i]; } delete array; max_col = 0; } INT_ROW & INT_ARRAY::operator[](int c) { if (c < 0 || c >= max_col) { cout << "Error ! exceeding array bounds\n"; exit (1); } return *array[c]; } main() { INT_ARRAY table(4, 5); table[1][2] = 2; cout << "table[1,2] " << table[1][2] << "\n"; } -- _Q _Q _Q _Q _Q_Q _Q _Q _Q /_\) /_\) /_\) /_\)/_/\\) /_\) /_\) Gary Powell /_\) _O|/O_O|/O__O|/O___O|/O_OO|/O__O|/O__O|/O__________________________________O|/O_ uunet!uw-beaver!sumax!ole!powell Seattle Silicon Corp. (206) 828-4422