On Monday, 29 January 2018 at 10:06:23 UTC, Simen Kjærås wrote:
On Monday, 29 January 2018 at 09:23:55 UTC, Sobaya wrote:
I found a strange behavior.

class A {
    void opAssign(int v) {}
}

class Test {
    A a;
    this() {
        a = new A(); // removing this causes compile error.
a = 3; // cannot implicitly convert expression `3` of `int` to `A`
    }
}

void main() {
    // this is allowed.
    A a;
    a = 3;
}

The first assignment in the constructor isn't actually a call to opAssign, it's a constructor call. In the same way, this will not compile:

A a = 3;

Also, since classes are reference types, you will need to construct an instance before assigning an int to it. The code in your main() will crash at runtime because the 'this' reference is null inside opAssign.

--
  Simen

I have not read https://dlang.org/spec/class.html
In 15.9, there is an explanation about it.
Sorry.

--
  Sobaya

Reply via email to