daniel@spica.ucsc.edu (Daniel Edelson) (01/03/90)
I have a container class for a pointer type. Is there a way to make -> work correctly w/o explicit coercion or using (*p).member? Quick example: struct object { int a; }; typedef object * Pobject; struct container { Pobject p; container(Pobject pp) : p(pp) { } operator Pobject() { return p; } object & operator * () { return *p; } }; main() { object o; container p = &o; (*p).a // works but unnatural style Pobject(p)->a // works but explicit coercion is ugly p->a; // doesn't work } I would the user-defined conversion to take place before the -> operator is applied, but that doesn't appear to be what the language specifies. I've tried 3 distinct compilers (cfront 2.0, oregon, g++) and they all behave the same. Help is greatly appreciated, Daniel Edelson daniel@cis.ucsc.edu
jimad@microsoft.UUCP (JAMES ADCOCK) (01/04/90)
try adding one line: object * operator->() { return p; } and a few missing semicolons. See the C++ Reference Manual pg 95 section 13.4.6.
beard@ux1.lbl.gov (Patrick C Beard) (01/05/90)
In article <10159@saturn.ucsc.edu> daniel@spica.ucsc.edu (Daniel Edelson) writes:
#I have a container class for a pointer type.
#Is there a way to make -> work correctly
#w/o explicit coercion or using (*p).member?
#
#Quick example:
#
#struct object {
# int a;
#};
#
#typedef object * Pobject;
#
#struct container {
# Pobject p;
# container(Pobject pp) : p(pp) { }
# operator Pobject() { return p; }
# object & operator * () { return *p; }
#};
#
#main()
#{
# object o;
# container p = &o;
#
# (*p).a // works but unnatural style
# Pobject(p)->a // works but explicit coercion is ugly
# p->a; // doesn't work
#}
The reason p->a doesn't work is that p is not a pointer to an object and
you haven't defined a member function operator->() for class container.
Define:
Pobject container::operator->() { return p; }
#
#I would the user-defined conversion to take place
#before the -> operator is applied, but that doesn't appear
#to be what the language specifies. I've tried 3 distinct
#compilers (cfront 2.0, oregon, g++) and they all behave the
#same.
#
It doesn't make sense for the conversion to be done since, in your example,
you aren't dereferencing "p" when you write p->; p isn't a pointer. So the
compilers are doing the right thing.
#Help is greatly appreciated,
#
#Daniel Edelson
#
#daniel@cis.ucsc.edu
-------------------------------------------------------------------------------
- Patrick Beard, Macintosh Programmer (beard@lbl.gov) -
- Berkeley Systems, Inc. ".......<dead air>.......Good day!" - Paul Harvey -
-------------------------------------------------------------------------------