static data in a sub-class
Steve D
whatchcallamit at weedline.com
Sat Dec 22 13:37:35 PST 2012
On Saturday, 22 December 2012 at 21:14:58 UTC, Ali Çehreli wrote:
> 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
Thanks for the options Ali, I could in fact just make the array a
parameter to f(), but I have lots of these calls to f() and
similar. I could also just duplicate f() in all my sub-classes,
but it's just code duplication. I will continue playing with your
suggestions etc to see what's cleanest.
Thanks
Steve
More information about the Digitalmars-d-learn
mailing list