home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #1 / NN_1993_1.iso / spool / comp / lang / cplus / 18699 < prev    next >
Encoding:
Internet Message Format  |  1993-01-05  |  1.6 KB

  1. Path: sparky!uunet!gatech!udel!wupost!waikato.ac.nz!canterbury.ac.nz!cantua!hugh
  2. Newsgroups: comp.lang.c++
  3. Subject: Re: Overloading [] for 2d+ matrixes
  4. Message-ID: <HUGH.93Jan5194117@kahu.cosc.canterbury.ac.nz>
  5. From: hugh@kahu.cosc.canterbury.ac.nz (Hugh Emberson)
  6. Date: Tue, 5 Jan 1993 07:41:17 GMT
  7. References: <1iarmlINN882@ub.d.umn.edu>
  8. Organization: Computer Science Dept., University of Canterbury, New Zealand
  9. In-Reply-To: cbusch@ub.d.umn.edu's message of 4 Jan 1993 20:27:33 -0600
  10. Nntp-Posting-Host: bkahu.canterbury.ac.nz
  11. Lines: 53
  12.  
  13. >>>>> On 4 Jan 1993 20:27:33 -0600, cbusch@ub.d.umn.edu (Chris) said:
  14.  
  15. Chris>    I been programming in C++ for quite a while now, but something
  16. Chris> occurred to me, how can you overload [] for 2d or 3d plus matrices?
  17. Chris> Apparently the only allowable syntax is:
  18. Chris>    myclass::operator [] (int);
  19.  
  20. There are two solutions that I have come across for dealing with this
  21. problem.
  22.  
  23. 1) The Elegant solution:
  24.  
  25. If you have a class X which contains a 2d array of Y's then define a
  26. helper class called, say Yrow, which just holds a pointer to a row in
  27. the array.  Then you have
  28.  
  29.     Yrow& X::operator [] (whatever);
  30.  
  31. which selects the row, and 
  32.  
  33.     Y& Yrow::operator [] (whatever);
  34.  
  35. which selects the column in that row.
  36. You use it like this.
  37.  
  38.     X a;
  39.  
  40.     a[i][j];
  41.  
  42. which expands to
  43.  
  44.     (a.operator[](i)).operator[](j);
  45.  
  46. This is how multidimensional arrays work in C/C++.
  47.  
  48. 2) The not so elegant solution.
  49.  
  50. Don't use [], use () instead.
  51.  
  52.     Y& X::operator () (whatever, whatever)
  53.  
  54. and use
  55.  
  56.     a(i,j);
  57.  
  58.  
  59. It should be a bit faster, but its not as pretty.  It has the same
  60. precedence as [] too.
  61.  
  62. Hugh
  63. --
  64. Hugh Emberson -- CS Postgrad
  65. hugh@cosc.canterbury.ac.nz
  66.