Path: utzoo!attcan!uunet!microsoft!jimad From: jimad@microsoft.UUCP (Jim ADCOCK) Newsgroups: comp.lang.c++ Subject: Re: Extensions to [] Message-ID: <55101@microsoft.UUCP> Date: 8 Jun 90 18:50:36 GMT References: <1589@ole.UUCP> Reply-To: jimad@microsoft.UUCP (Jim ADCOCK) Organization: Microsoft Corp., Redmond WA Lines: 109 In article <1589@ole.UUCP> powell@ole.UUCP (Gary Powell) writes: >I am new to C++ but after a seminar and some play time I tried writting >a class for two diminsional arrays. 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. Why not use the (int,int) >operator? Well I was using that for the initialization. It would seem to >me that since C allows array[][] access that C++ should allow overloading >of this also. > >With this background has there been any discussion on the overloading of >[][] ....[]? > >And is this a reasonable extension to the language? No, it shouldn't be necessary, and [][] is not one operator but two. Changing [][] from two operators to one would significantly change C++ from the C past. And doing so shouldn't be necessary. There are two common tricks used by people doing 2-dim [or n-dim] arrays in C++. Examples follow. The first trick is to build up your objects from rows and columns as the two [] operators implies. The second trick is to return a proxy object from the first application of [], that "remembers" where you are in the 2-dim [n-dim] array after the first application, and then the second application of [] is applied to the proxy object, which "remembers" the previous index, and thus has all the information necessary to return the correct element in the 2-dim [n-dim] array. BUT: be forwarned there are a fair amount of C and/or C++ compilers out there that have a hard time correctly compiling the code necessary to do proxies! // Example of building up a two dimemsional array one dimension at a time: extern "C" { #include "stdio.h" } class COL { public: int c[10]; int& operator[](int i) { printf("COL[%d] ",i); return c[i]; } }; class MAT { public: COL r[10]; COL& operator[](int j) { printf("ROW[%d] ",j); return r[j]; } }; main() { MAT mat; mat[5][6] = 56; printf("\n"); mat[6][5] = 65; printf("\n"); printf("mat[5][6] %d\n", mat[5][6]); printf("mat[6][5] %d\n", mat[6][5]); } // example of using proxies: extern "C" { #include "stdio.h" } #include "shortnew.h" typedef int* PI; class PROXY { const PI c; public: PROXY(const PI cc) : c(cc) {} int& operator[](int i) const { printf("COL[%d] ",i); return c[i]; } }; class MAT { int i[100]; public: PROXY operator[](int j) const { printf("ROW[%d] ",i); return &(i[j*10]); } }; main() { MAT mat; mat[5][6] = 56; printf("\n"); mat[6][5] = 65; printf("\n"); printf("mat[5][6] %d\n", mat[5][6]); printf("mat[6][5] %d\n", mat[6][5]); }