struct and class member alias

Jarrett Billingsley kb3ctd2 at yahoo.com
Tue Jun 5 11:26:37 PDT 2007


"Stuart Murray" <stuart.w.murray at fakey.nospambots.gmail.com> wrote in 
message news:f4430d$14oc$1 at digitalmars.com...
> In the following, the aliases have no apparent effect (although they do 
> compile). Is there a way to achieve a similar effect? I just want to be 
> able to access
> boxInstance.pos.x
> using
> boxInstance.x

It doesn't compile; I get

foo.d(19): Error: pos.x is used as a type
foo.d(20): Error: pos.y is used as a type
foo.d(21): Error: size.x is used as a type
foo.d(22): Error: size.y is used as a type

It's no surprise, either.  You're not allowed to make aliases of 
expressions.

What you can do is make "properties."  You have a setter and a getter for 
each property.  Because of some syntactic sugar, you can write "a.x" to mean 
"a.x()" and "a.x = 5" to mean "a.x(5)".

Here's the Box class with read/write properties for x and y defined.

public class Box
{
    Coord pos, size;

    this(in int x, in int y, in int w, in int h)
    {
        pos  = new Coord(x, y);
        size = new Coord(w, h);
    }

    public int x()
    {
        return pos.x;
    }

    public void x(int val)
    {
        pos.x = val;
    }

    public int y()
    {
        return pos.y;
    }

    public void y(int val)
    {
        pos.y = val;
    }
}

It's a little more verbose than you might like.

Another solution would be to make public reference fields in Box that refer 
to the inner pos.x, pos.y etc. members.  But D doesn't have generic 
reference types, so foo :( 




More information about the Digitalmars-d-learn mailing list