On 12/22/2012 12:44 PM, Steve D wrote:
Hello,
How can I get class B's array printed, using inherited A's function?
(Dmd 2.060)
class A {
static float[3] hi = 1;
void f() { writefln("hi %s",hi); }
}
class B : A {
static float[3] hi = 2;
}
B b = new B();
b.f(); // prints 'hi [1,1,1]'
// can I get it to use B's overridden hi: [2,2,2] ?
Thanks for your help :)
Steve
One way is to present the data to the superclass during construction:
import std.stdio;
class A {
const float[] hi;
this(float[] hi) {
this.hi = hi;
}
void f() { writefln("hi %s",hi); }
}
class B : A {
static float[3] hi = 2;
this() {
super(hi);
}
}
void main()
{
B b = new B();
b.f();
}
Another ways is for A to require that the subclasses present the data by
a member function:
import std.stdio;
class A {
abstract float[] hi_data();
void f() { writefln("hi %s", hi_data()); }
}
class B : A {
static float[3] hi = 2;
override float[] hi_data() {
return hi;
}
}
void main()
{
B b = new B();
b.f();
}
Orthogonally, if f() is strictly on the A interface, then you can make
it a final function:
final void f() { writefln("hi %s", hi_data()); }
Ali