Path: utzoo!attcan!uunet!lll-winken!elroy.jpl.nasa.gov!ames!eos!shelby!csli!keith From: keith@csli.Stanford.EDU (Keith Nishihara) Newsgroups: comp.lang.c++ Subject: Re: Extensions to [] Message-ID: <13984@csli.Stanford.EDU> Date: 7 Jun 90 16:23:52 GMT References: <1589@ole.UUCP> Sender: keith@csli.Stanford.EDU (Keith Nishihara) Reply-To: Neil Hunt Organization: Center for the Study of Language and Information, Stanford U. Lines: 111 In <1589@ole.UUCP> powell@ole.UUCP (Gary Powell) writes: >[...] What I found myself wanting was >a overloaded operator [][](int)(int). However my GNU g++ 1.35 compiler >complains bitterly when I tried to code this. You can do it in the obvious way using two applications of operator[]. If you want to do checking or other additional functions on both indeces, you will need to define a half way class which is returned from the first application of operator[], and which serves simply as a base for the second operator[]. For example: #include // Declarations. class A; class Half; // Define class A which is a 2D array. class A { public: A(); Half & operator[] (int); private: friend class Half; int x; int y; int *data; }; // Constructor simply sets up a dummy array and initialises it. A::A() { x = 5; y = 10; data = new int[x * y]; for(int j = 0; j < x * y; j++) data[j] = j; } // Define class Half which is a placeholder for the half decoded array access. class Half { public: int operator[] (int); private: friend class A; int * a; // half decoded access. A * from; // pointer to original array. }; // First half of array access. Half & A::operator[] (int j) { printf("A::operator[%d]\n", j); static Half h; if(j < 0) // Range checking. j = 0; if(j >= y) j = y-1; h.a = data + j*x; // Part access. h.from = this; // So that Half can get to array dimensions. return h; // Return reference to local static Half. } // Second half of array access. int Half::operator[] (int i) { printf("Half::operator[%d]\n", i); if(i < 0) // Range checking. i = 0; if(i >= from->x) i = from->x - 1; return a[i]; // Rest of access. } main() { A array; printf("Normal access: %d\n\n", array[2][3]); printf("Out of bounds in first half: %d\n\n", array[20][3]); printf("Out of bounds in second half: %d\n\n", array[2][30]); } // Gives results: // // A::operator[2] // Half::operator[3] // Normal access: 13 // // A::operator[20] // Half::operator[3] // Out of bounds in first half: 48 // // A::operator[2] // Half::operator[30] // Out of bounds in second half: 14 Neil/. Neil%teleos.com@ai.sri.com