使用类引用的多态性和继承(第2部分)?

时间:2014-05-13 10:03:03

标签: class delphi inheritance reference polymorphism

下面的控制台应用程序给出了"运行时错误" ...

为什么会这样?非常感谢 !

PS:Related SO post

program Project2;

{$APPTYPE CONSOLE}

type
  TParent = class;
  TParentClass = class of TParent;

  TParent = class
  public
    procedure Work; virtual; abstract;
  end;

  TChild1 = class(TParent)
  public
    procedure Work; override;
  end;

  TChild2 = class(TParent)
  public
    procedure Work; override;
  end;

procedure TChild1.Work;
begin
  WriteLn('Child1 Work');
end;

procedure TChild2.Work;
begin
  WriteLn('Child2 Work');
end;

procedure Test(ImplClass: TParentClass);
var
  ImplInstance: TParent;
begin
  ImplInstance := ImplClass.Create;
  ImplInstance.Work;
  ImplInstance.Free;
end;

begin
  Test(TParent);
  Test(TChild1);
  Test(TChild2);
  Readln;
end.

1 个答案:

答案 0 :(得分:6)

TParent.Work方法声明为abstractdocumentation说:

  

您只能在已覆盖该方法的类的类或实例中调用抽象方法。

当您致电TParent.Work时,您违反了该规则,因此遇到运行时错误。