質問

The console application below gives "Runtime error"...

Why would this happen ? Many thanks !

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.
役に立ちましたか?

解決

The TParent.Work method is declared as abstract. The documentation says:

You can call an abstract method only in a class or instance of a class in which the method has been overridden.

When you call TParent.Work you break that rule and so encounter a runtime error.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top