home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / std / cplus / 905 < prev    next >
Encoding:
Text File  |  1992-07-21  |  1.9 KB  |  51 lines

  1. Newsgroups: comp.std.c++
  2. Path: sparky!uunet!zaphod.mps.ohio-state.edu!moe.ksu.ksu.edu!ux1.cso.uiuc.edu!m.cs.uiuc.edu!sunb10.cs.uiuc.edu!sparc1.cs.uiuc.edu!pjl
  3. From: pjl@sparc1.cs.uiuc.edu (Paul Lucas)
  4. Subject: Re: How do I... (regarding overloading)
  5. Message-ID: <1992Jul21.232959.13540@sunb10.cs.uiuc.edu>
  6. Sender: news@sunb10.cs.uiuc.edu
  7. Organization: University of Illinois at Urbana-Champaign
  8. References: <1992Jul21.144856.583@ualr.edu>
  9. Distribution: usa
  10. Date: Tue, 21 Jul 1992 23:29:59 GMT
  11. Lines: 38
  12.  
  13. In <1992Jul21.144856.583@ualr.edu> choate@acs.harding.edu (Brad S. Choate) writes:
  14.  
  15. *****>    For starters, this type of question belongs in comp.lang.c++.
  16.  
  17. >Ok... I'm new at this business, so this should be easy for some of the experts
  18. >out there.
  19.  
  20. >I know about operator overloading and I can implement it to some degree without
  21. >consulting the manuals too much, but I'm stuck on this one:
  22.  
  23. >    a[1]=x;
  24.  
  25. >Ok.  "a" is an object that I have created and I've overloaded the [] operator
  26. >to allow me to return a value at position "1" (in this case) from my object.
  27. >However, in this case, I'm not needing output, I'm trying to _assign_ a value
  28. >to that position.  I know how to overload the "=" operator, but _how_ do you
  29. >do _both_ operators at the same time?
  30.  
  31. *****>    operator= has got nothing to do with it unless the thing that []
  32.     returns is itself a class object (in which case operator= would
  33.     be overloaded in _that_ class--whether operator= is overloaded
  34.     in _this_ class is irrelevant...unless you're doing something
  35.     non-canonical).  operator[] should return a reference to the
  36.     thing...that's it; the assignment just happens.  
  37.  
  38.         class IntVect {
  39.             int *v;
  40.         public:
  41.             // ...
  42.             int &operator[]( int i ) { return v[i]; }
  43.         };
  44.     
  45.     This is a naive example in that it doesn't do bounds-checking nor
  46.     automatic "growing."
  47. -- 
  48.     - Paul J. Lucas                University of Illinois    
  49.       AT&T Bell Laboratories        at Urbana-Champaign
  50.       Naperville, IL            pjl@cs.uiuc.edu
  51.