override toString

Michal Minich michal.minich at gmail.com
Thu Dec 3 02:18:53 PST 2009


Hello Qian,

> Hi All,
> 
> I want to print some object information for debugging. But the name of
> class is incorrect. I do not know why.
> 
> module test;
> 
> class A {
> char[] data;
> public char[] toString() {
> return "<" + this.classinfo.name + ": " + data + ">";
> }
> }
> class B: A {
> char[] data2;
> public override char[] toString() {
> return "<" + this.classinfo.name + ": " + super.toString + ", " +
> data2
> + ">";
> }
> }
> auto b = new B;
> b.data = "hello";
> b.data2 = "world";
> Cout(b.toString); // <test.B: <test.B: hello>, world>
> The expected result should be:
> <test.B: <test.A: hello>, world>
> But the actual result is:
> <test.B: <test.B: hello>, world>

use typeof(this).classinfo.name to get type of A. "this" returns runtime 
type of instance, "typeof(this)" return static type.

http://www.digitalmars.com/d/1.0/expression.html

btw. I noticed that you are using "+" for string concatenation, how is possible 
that your program even comiples??? "~" should be used for string concatenation.




More information about the Digitalmars-d-learn mailing list