home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!gatech!udel!wupost!waikato.ac.nz!canterbury.ac.nz!cantua!hugh
- Newsgroups: comp.lang.c++
- Subject: Re: Overloading [] for 2d+ matrixes
- Message-ID: <HUGH.93Jan5194117@kahu.cosc.canterbury.ac.nz>
- From: hugh@kahu.cosc.canterbury.ac.nz (Hugh Emberson)
- Date: Tue, 5 Jan 1993 07:41:17 GMT
- References: <1iarmlINN882@ub.d.umn.edu>
- Organization: Computer Science Dept., University of Canterbury, New Zealand
- In-Reply-To: cbusch@ub.d.umn.edu's message of 4 Jan 1993 20:27:33 -0600
- Nntp-Posting-Host: bkahu.canterbury.ac.nz
- Lines: 53
-
- >>>>> On 4 Jan 1993 20:27:33 -0600, cbusch@ub.d.umn.edu (Chris) said:
-
- Chris> I been programming in C++ for quite a while now, but something
- Chris> occurred to me, how can you overload [] for 2d or 3d plus matrices?
- Chris> Apparently the only allowable syntax is:
- Chris> myclass::operator [] (int);
-
- There are two solutions that I have come across for dealing with this
- problem.
-
- 1) The Elegant solution:
-
- If you have a class X which contains a 2d array of Y's then define a
- helper class called, say Yrow, which just holds a pointer to a row in
- the array. Then you have
-
- Yrow& X::operator [] (whatever);
-
- which selects the row, and
-
- Y& Yrow::operator [] (whatever);
-
- which selects the column in that row.
- You use it like this.
-
- X a;
-
- a[i][j];
-
- which expands to
-
- (a.operator[](i)).operator[](j);
-
- This is how multidimensional arrays work in C/C++.
-
- 2) The not so elegant solution.
-
- Don't use [], use () instead.
-
- Y& X::operator () (whatever, whatever)
-
- and use
-
- a(i,j);
-
-
- It should be a bit faster, but its not as pretty. It has the same
- precedence as [] too.
-
- Hugh
- --
- Hugh Emberson -- CS Postgrad
- hugh@cosc.canterbury.ac.nz
-