Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!bcm!dimacs.rutgers.edu!aramis.rutgers.edu!paul.rutgers.edu!njin!uupsi!sunic!isgate!krafla!heimir From: heimir@rhi.hi.is (Heimir Thor Sverrisson) Newsgroups: comp.lang.c++ Subject: operator[][] ? Keywords: operator[] Message-ID: <3286@krafla.rhi.hi.is> Date: 20 Jun 91 13:24:33 GMT Sender: usenet@rhi.hi.is Lines: 103 Hi fellow Netlanders, is there anyone out there that can help me understand why the following code works! I'm trying to build a class that contains integer data that should be organized as a two-dimensional array (of fixed dimensions). I was trying to implement an operator that would allow me to use code like: Status st; st[TOTAL][COD]=123; where Status is the name of my class and the [][] notation would allow me to manipulate that element in my private array. On top of the well known problem of not being able to detect if I'm being used as an l- or r-value I also ran into trouble defining the operator(s) involved to do this. What I ended up with were two operator[]'s and the code did actually work in g++ 1.39. The implementation is : int* Status::operator[](int index) { return stat[index]; // private: int stat[i][j] } int& Status::operator[](int* iarr) { return *iarr; } And I'm asking you why does this work? If it is not a compiler bug/feature, how can I access the latter index (COD) from within the second member function above (i.e. to test it's range)? Following is the whole code that I used to test this: --------------------------------------------------------------------------- // Status.h // Declare the Status-class. // #ifndef Status_h #define Status_h #define S_LINES 13 #define S_COL 10 class Status { public: Status(int num); int* operator[](int index); int& operator[](int *iarr); ~Status(); private: stat[S_LINES][S_COL]; int recalc; }; #endif --------------------------------------------------------------------------- // Status.cc // Implementation of the Status-class. // #include "Status.h" Status::Status(int num) { for(int i=0; i < S_LINES; i++) for(int j=0; j < S_COL; j++) stat[i][j] = i*S_COL+j; // Set to zero!! } int* Status::operator[](int index) { return stat[index]; } int& Status::operator[](int* iarr) { return *iarr; } --------------------------------------------------------------------------- // tStatus.cc // // Test the status class // #include #include "Status.h" main() { Status st(1337); for(int i=0; i < S_LINES; i++){ for(int j=0; j < S_COL; j++) cout << st[i][j] << " "; cout << "\n"; } } --------------------------------------------------------------------------- I hope somebody out there can clear up this matter, 'cause in the meantime I'll have to make the 'stat' array public, and cannot test range, nor detect potential recalc operation :-( -- Heimir Thor Sverrisson heimir@plusplus.is Laugavegi 13 101 Reykjavik Iceland