Newbie: copy, assignment of class instances
bearophile
bearophileHUGS at lycos.com
Thu May 20 16:13:23 PDT 2010
Larry Luther:
> void copy (in A a) {
In D2 it's better to use "const" or "immutable" instead of "in".
Here's one version of the code const-aware:
import std.stdio: writeln;
import std.string: format;
template ExceptionTemplate() {
this() {
super(this.classinfo.name);
}
this(string msg) {
super(this.classinfo.name ~ ": " ~ msg);
}
}
class ArgumentException: Exception {
mixin ExceptionTemplate;
}
class A {
int x, y;
this(int xx, int yy) {
this.x = xx;
this.y = yy;
}
void copyFrom(const Object other) {
const o = cast(typeof(this))other;
if (o is null)
throw new ArgumentException("Some message here...");
x = o.x;
y = o.y;
}
override string toString() const {
return format("A(%d, %d)", this.x, this.y);
}
}
class B : A {
int z;
this(int xx, int yy, int zz) {
super(xx, yy);
this.z = zz;
}
override void copyFrom(const Object other) {
const o = cast(typeof(this))other;
if (o is null)
throw new ArgumentException("Some message here...");
super.copyFrom(other);
z = o.z;
}
override string toString() const {
return format("B(%d, %d, %d)", this.x, this.y, this.z);
}
}
void main() {
B foo = new B(1, 2, 3);
B bar = new B(4, 5, 6);
writeln("foo = ", foo);
writeln("bar = ", bar);
foo.copyFrom(bar);
writeln("foo = ", foo);
writeln("bar = ", bar);
}
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list