How to define a constructor in a struct?
Adam D. Ruppe
destructionator at gmail.com
Sun Aug 5 09:16:44 PDT 2012
On Sunday, 5 August 2012 at 16:05:54 UTC, Minas Mina wrote:
> I want to make a struct that defines a constructor:
You can't quite do it. A D struct is supposed to always be
trivial to initialize. You can, however, do a static opCall(),
constructors that take parameters, and/or disable default
construction, forcing the user to use one of those other ones.
> I wrote a @disable next to it but same error. I don't
> understand what the "no body" part means.
You'd write it
@disable this();
What this does is say this struct can't be default defined - the
user would have to initialize it using one of its other
constructors.
For example:
struct Test {
@disable this(); // this makes it so Test t; won't work - you
have to use a constructor of some sort
this(int num) {
// construct it using the number
}
// static opCall makes Test() work when you spell it out
static Test opCall() {
Test t = Test(1);
return t;
}
}
void main() {
//Test t; // compile error - default construction is diabled
Test t = Test(); // uses opCall
Test t2 = Test(5); // uses the constructor with an int param
}
More information about the Digitalmars-d-learn
mailing list