【发布时间】:2014-05-13 09:41:59
【问题描述】:
下面控制台应用程序的输出是
Parent
Parent
Parent
而不是
Parent
Child1
Child2
为什么会这样?此外,如何获得预期的输出?非常感谢!
PS: 看完related SO post还是没有头绪...
program Project1;
{$APPTYPE CONSOLE}
type
TParent = class;
TParentClass = class of TParent;
TParent = class
public
ID: string;
constructor Create;
end;
TChild1 = class(TParent)
public
constructor Create;
end;
TChild2 = class(TParent)
public
constructor Create;
end;
constructor TParent.Create;
begin
ID := 'Parent';
end;
constructor TChild1.Create;
begin
ID := 'Child1';
end;
constructor TChild2.Create;
begin
ID := 'Child2';
end;
procedure Test(ImplClass: TParentClass);
var
ImplInstance: TParent;
begin
ImplInstance := ImplClass.Create;
WriteLn(ImplInstance.ID);
ImplInstance.Free;
end;
begin
Test(TParent);
Test(TChild1);
Test(TChild2);
Readln;
end.
【问题讨论】:
-
注意我编辑了代码。您并不是要在每个派生类中添加新的
ID字段,以隐藏在TParent中声明的内容。