Path: utzoo!attcan!uunet!cs.utexas.edu!milano!cadillac!puma!vaughan From: vaughan@puma.cad.mcc.com (Paul Vaughan) Newsgroups: comp.lang.c++ Subject: Re: problems with [] operator Message-ID: <9300@cadillac.CAD.MCC.COM> Date: 29 Jun 90 15:18:04 GMT Sender: news@cadillac.CAD.MCC.COM Lines: 75 From: reberhar@ethz-inf (Rolf Georg Eberhardt) hi everybody, I've encountered a problem concerning the [] operator. I've defined following class: typedef class foo *foo_p; class foo { public: foo_p next, list; // each object of foo may contain a list of other "foo's" foo_p operator [] (ndx); }; foo_p foo::operator [] (ndx) { foo_p tmp = list; // ... run thru list starting at list and return the ndx'th element return(tmp); }; I get following error msg's : void foo::do_something(foo_p b) { list[i]->next = b; // error : non pointer -> next b->next = a[i]; // error : bad assignment type: foo_p = foo ... }; list is a foo*, list[i] is a foo--not the result of applying the operator [] to a foo, just the usual array [] on a foo*. Try (*list)[i] if you wanted to invoke foo::operator[]. In all C++ books I've looked into the []-operator must return a reference. Why - on the other hand - does following code compile and run correctly ? typedef class bb *bb_p; class bb { public: bb_p next; int key; // etc... }; class cc { public: bb_p list; bb_p operator[] (int ndx); // same code as above }; void main() { cc c; // do some initializing .. c[2]->key = 4; cout << c[2]->key; }; The operator[] can return whatever you want--no restriction to references. That's just a common usage. Here c is a cc (not a cc*, like above), thus c[2] invokes cc::operator[] which returns a bb*. The bb* (being a pointer) can be deferenced using -> to get the key field, so the code compiles fine. -- Paul Vaughan, MCC CAD Program | ARPA: vaughan@mcc.com | Phone: [512] 338-3639 Box 200195, Austin, TX 78720 | UUCP: ...!cs.utexas.edu!milano!cadillac!vaughan Paul Vaughan, MCC CAD Program | ARPA: vaughan@mcc.com | Phone: [512] 338-3639 Box 200195, Austin, TX 78720 | UUCP: ...!cs.utexas.edu!milano!cadillac!vaughan