Named constructors
Alex
sascha.orlov at gmail.com
Wed Jan 9 08:53:40 UTC 2019
On Wednesday, 9 January 2019 at 07:47:02 UTC, Dru wrote:
> Another way to distinguish between constructors is needed.
> Because it is possible to have two different constructors that
> take the same arguments.
> Adding dummy arguments that are unused hurts code clarity.
Couldn't this problem be solved by a factory method? I mean,
either this, or something like this:
http://www.cs.technion.ac.il/users/yechiel/c++-faq/named-ctor-idiom.html
´´´
import std.stdio;
import std.math;
void main()
{
auto pr = Point.rectangular(2,3);
assert(approxEqual(pr.x_, 2));
assert(approxEqual(pr.y_, 3));
auto pp = Point.polar(1,PI);
assert(approxEqual(pp.x_, -1));
assert(approxEqual(pp.y_, 0));
}
struct Point {
public:
static Point rectangular(real x, real y) // Rectangular
coord's
{
return Point(x,y);
}
static Point polar(real radius, real angle) // Polar
coordinates
{
return Point(radius * cos(angle), radius * sin(angle));
}
private:
this(real x, real y)
{
x_ = x;
y_ = y;
}
real x_, y_;
}
´´´
More information about the Digitalmars-d
mailing list