check type

spir denis.spir at gmail.com
Sun Nov 7 03:42:13 PST 2010


On Sat, 06 Nov 2010 20:50:05 -0400
bearophile <bearophileHUGS at lycos.com> wrote:

> spir:
> 
> > class SC {
> >     string f = "SC";
> >     void show() {writeln(this.f);}
> > }
> > class C : SC {
> >     string f = "C";
> > }
> > void main () {
> >     auto c = new C();
> >     writeln(c.f) ;  // OK, got "C"
> >     c.show() ;      // expected "C", got "SC"
> >     
> >     // below test for type
> >     if (is(typeof(c) == C)) {writeln("type C");} else {writeln("type SC");}
> >     auto sc = new SC();
> >     if (is(typeof(sc) == C)) {writeln("type C");} else {writeln("type SC");}
> > }
> 
> Java acts as D here:
> http://ideone.com/LcAll
> 
> C# requires the new keyword:
> http://ideone.com/AVFvI
> 
> 
> A D version that does as you desire:
> 
> import std.stdio;
> class SC {
>     string f_ = "SC";
>     @property string f() { return f_; }
>     void show() { writeln(this.f); }
> }
> class C : SC {
>     string f_ = "C";
>     @property override string f() { return f_; }
> }
> void main () {
>     auto c = new C();
>     writeln(c.classinfo.name);
> 
>     auto sc = new SC();
>     writeln(sc.classinfo.name);
> 
>     writeln(c.f); // "C"
>     c.show(); // "C"
> }
> 
> Bye,
> bearophile

I just realised that what I was asking for is in fact class-level fields -- common to all instances, instead of each instance having it locally.

Denis
-- -- -- -- -- -- --
vit esse estrany ☣

spir.wikidot.com



More information about the Digitalmars-d-learn mailing list