Problem with Point property
Hasan Aljudy
hasan.aljudy at gmail.com
Tue Mar 6 13:43:29 PST 2007
Henning Hasemann wrote:
> Hi all, say I have a structure Point and an attribute position like this:
>
> struct Point {
> int x, y;
> }
>
> class Foo {
> Point position;
> }
>
> So far, so good. Now I want to substitude the attribute with a property
> (because I want to react on changes of the position immediately)
> The setter is no Problem:
>
> void position(Point p) { mPosition = p; react(); }
>
> The getter indeed is. If I wrote:
>
> Point position() { return mPosition; }
>
> this would break expressions like
>
> Foo().position.x = 5;
>
> which I happen to use often.
> The solutions I see are
>
> * Return a proxy object instead of a real Point.
> Bad because the return type is not Point anymore.
>
> * Return a Point*, would break types too I dont
> know if these two even work.
>
> * Turn Point into a class so I return a reference.
> Possible, but Point really just carries 2 integers
> and I either had to change all "Point(...)"'s into "new Point(...)"'s,
> or implement opCall for a class which I'm not sure if it is the best
> option, since it may be misleading.
>
> Are there other ways? Can I somehow return a reference to a struct
> without "leaving" the type?
>
> What would you do?
>
> TIA,
> Henning
>
If you return a pointer, you can still use the . operator, so I think
foo().point.x;
should work just fine (both syntactically and semantically)
However the implication is that if you have a function that takes a
point struct object, you either have to change that function to take a
point pointer, or dereference the property every time you pass it to
functions.
More information about the Digitalmars-d
mailing list