Function Overloading
Salih Dincer
salihdb at hotmail.com
Tue Oct 31 20:09:44 UTC 2023
```d
struct Calculate
{
int memory;
string result;
auto toString() => result;
this(string str)
{
add(str);
}
this(int num)
{
add(num);
}
import std.string : format;
void add(string str)
{
result ~= str.format!"%s + ";
}
void add(int num)
{
memory += num;
add(num.format!"%s");
}
}
import std.stdio;
void main()
{
// without constructor:
Calculate c;
c.add("x");
c.add(2);
c.writeln; // x + 2 +
// with constructor:
c = Calculate("x");
c.add(2);
c.writeln; // x + 2 +
}
```
There is a simple struct like the one above that is not related
to reality. There can be more than 2 function overloading in it,
but in our example there are only 2. Without implementing a
similar function again for each constructor; is it possible to do
something like `alias add = this;`?
```d
struct Calculate
{
int memory;
string result;
auto toString() => result;
// alias add = this;
import std.string : format;
this(string str)
{
result ~= str.format!"%s + ";
}
this(int num)
{
memory += num;
add(num.format!"%s");
}
}
```
SDB at 79
More information about the Digitalmars-d-learn
mailing list