On 03/23/2011 06:48 AM, teo wrote:
How can I use properties with increment/decrement and +=/-= operators?

I did following tests (the errors are from dmd v2.052):

class T
{
     private int _x;
     @property
     public int x() { return _x; }
}

void main()
{
     int[] a;
     // case #1.1
     a.length++;    // Error: a.length is not an lvalue
     // case #1.2
     a.length += 1; // Ok


     auto t = new T();
     // case #2.1
     t.x++;      // Error: t.x() is not an lvalue
     // case #2.2
     t.x += 1;   // Error: 't.x' is not a scalar, it is a @property int()
                 // Error: incompatible types for ((t.x) += (1)):
'@property int()' and 'int'
     // case #2.3
     t.x()++;    // Error: t.x() is not an lvalue
     // case #2.4
     t.x() += 1; // Error: t.x() is not an lvalue
}

Basically I want to change the value of a member variable, which is
accessed only through a property.
It looks like that is partially possible with the length property of
dynamic arrays although they probably are implemented in a different way.

You need a "write" property:

    @property
    {
        public int x() { return _x; } // Read property
        public void x(int x1) { _x = x1; } // Write property
    }

As for the dynamic array length property:

void main()
{
    int[] a;
    ++a.length; // Works
    a.length += 1; // Works
    a.length++; // Error: a.length is not an lvalue
}

I don't get why the error on a.length++ either. I'm curious about the answer.

Reply via email to