home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!haven.umd.edu!darwin.sura.net!jvnc.net!newserver.jvnc.net!newsserver.technet.sg!nuscc!papaya!suresh
- From: suresh@papaya.iss.nus.sg (Suresh Thennarangam - Research Scholar)
- Subject: Re: Overloading [] for 2d+ matrixes
- Message-ID: <1993Jan5.094647.7830@nuscc.nus.sg>
- Sender: usenet@nuscc.nus.sg
- Reply-To: suresh@iss.nus.sg (Suresh Thennarangam - Research Scholar)
- Organization: Institute Of Systems Science, NUS
- References: <1iarmlINN882@ub.d.umn.edu>
- Date: Tue, 5 Jan 1993 09:46:47 GMT
- Lines: 82
-
- In article <1iarmlINN882@ub.d.umn.edu> cbusch@ub.d.umn.edu (Chris) writes:
- > I been programming in C++ for quite a while now, but something
- >occurred to me, how can you overload [] for 2d or 3d plus matrices?
- >Apparently the only allowable syntax is:
- > myclass::operator [] (int);
-
- Yes, that is so but it is quite easy if you adopt the following approach:
-
- 1> Define an operator[] function for vector class (1 d array) which returns
- a reference to the correct element
-
- 2 >Your 2D matrix class is derived from this class and also has it's own
- operator[] function that returns a reference to an instance of the
- vector class
-
- so if you have
-
- class vector
- {
- public:
- vector(int) { ... };
- int& operator[](int) { ...} // return appropriate data value
- protected:
- int * data;
- :
- :
- };
-
- class matrix: public vector
- {
- public:
- matrix(int,int) { ... };
- vector& operator[](int) { ...}
-
- }
-
- matrix a(3,3) ;
-
- a[2][2] = 10 ;
-
- cout << a[2][2] ; // not sure if cout will accept a reference to an integer.
- // will someone confirm please ?
-
-
- A simpler way would be for the matrix class to return an array which
- can already accept the subscript operator( i.e. []). This can be
- extended to higher dimensions so a matrix_3d class can return a
- int ** pointer which can already accept the [] operators so
- you can have a statement like
-
- class matrix_3d
- {
- public:
- int ** operator[]( int) { ....}
- :
- :
- :
- }
- matrix_3d m_3d(3,3,3) ;
- m_3d[2][2][2] = 0 ;
-
- This is rather inelegant because you can't do range checking on
- some of the subscripts and also you are exposing the private
- data of the classes. The first method is type safe and can be
- nicely extended to higher dimensions( albeit a bit tedious to
- implement).
-
-
- Hope that answers your question.
-
- __
- (_ / / o_ o o |_
- __)/(_( __) (_(_ /_)| )_
-
- ***************************************************************************
- * Suresh Thennarangam * EMail: suresh@iss.nus.sg(Internet) *
- * Research Scholar * ISSST@NUSVM.BITNET *
- * Institute Of Systems Science * Tel: (065) 772 2588. *
- * National University Of Singapore * Facs.: (065) 778 2571 *
- * Heng Mui Keng Terrace * Telex: ISSNUS RS 39988 *
- * Singapore 0511. * *
- ***************************************************************************
-