Anonymous user
Polymorphic copy: Difference between revisions
Converted both D entries from D1+Tango => D2+Phobos (I can't test Tango code)
(Converted both D entries from D1+Tango => D2+Phobos (I can't test Tango code)) |
|||
Line 486:
=={{header|D}}==
If we assume there are no data members, this will be quite short and simple:
<lang
▲ char[] toString() { return "I'm the instance of T"; }
T duplicate() { return new T; }
}
class S : T {
override T duplicate() { return new S; }
}
void main () {
import std.stdio;
T orig = new S;
T copy = orig.duplicate();
}</lang>
{{out}}
<pre>I'm the instance of S
I'm the instance of S</pre>
do the deep copy.
<lang
▲ this(T t = null) { } // ctor that will be used for copying
▲ char[] toString() { return "I'm the instance of T"; }
T duplicate() { return new T(this); }
}
class S : T {
char[] str;
this(S s = null) {
super(s);
if (s
str =
else
str =
}
override string toString() {
}
▲ char[] toString() { return "I'm the instance of S p: " ~ str; }
override T duplicate() { return new S(this); }
//
override bool custom(char c) {
return str is null;
}
}
void main () {
import std.stdio;
T orig = new S;
orig.custom('X');
T copy = orig.duplicate();
orig.custom('Y');
}</lang>
{{out}}
<pre>I'm the instance of S p: Y23
I'm the instance of S p: X23</pre>
=={{header|E}}==
|