On Sunday, 8 January 2017 at 09:22:12 UTC, collerblade wrote:
How can i do opOpAssign with properties??

1. If you want the member variable to change, naturally, you should provide a getter property which returns a reference to that variable:

    ref Point location() @property {
      return m_location;
    }

This alone solves the immediate problem.

2. Note that it is common for assignment expressions to return a reference to the result, which would, for example, make chains like "a = (b += c)" possible:

  ref Point opOpAssign(string op)(in Point p) if (op == "+") {
    x+=p.x;
    y+=p.y;
    return this;
  }

Here's a complete working version of your example:

-----
struct Point {
  float x=0,y=0;

  this(float _x, float _y) {
    x=_x;
    y=_y;
  }

  //opopassign for +=
  ref Point opOpAssign(string op)(in Point p) if (op == "+") {
    x+=p.x;
    y+=p.y;
    return this;
  }
}

class A {
  public:
    ref Point location() @property {
      return m_location;
    }

    void location(in Point newlocation) @property {
      m_location=newlocation;
    }

  private:
    Point m_location;
}

void main() {
  import std.stdio;
  auto a= new A;
  a.location+=Point(1,1);
  writeln (a.location); // Point(1, 1)
  a.location+=Point(1,1);
  writeln (a.location); // Point(2, 2)
}
-----

Ivan Kazmenko.

Reply via email to