the behavior of opAssign
Simen Kjærås
simen.kjaras at gmail.com
Mon Jan 29 10:06:23 UTC 2018
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
More information about the Digitalmars-d-learn
mailing list