为什么不调用后代的抽象基类方法版本?

时间:2011-12-15 15:20:12

标签: delphi interface abstract

我正在尝试创建一个简单的类THistory,它有一个过程,它接受一个实现简单接口的抽象基类。

下面的代码编译,但是THistory类调用基类HistoryRecords抽象Insert proc而不是传入的子类Insert proc。我错过了什么?

感谢您的帮助!

unit uHistory;

interface

uses Dialogs;

type

IHistoryRecord = interface
  ['{67C90064-1667-4DE0-AF52-11B6E5A00892}']
  procedure Insert();
end;

THistoryRecord = class abstract(TInterfacedObject, IHistoryRecord)
  procedure Insert(); virtual; abstract;
end;

THistory = class(TObject)
  public
  procedure Add(pHistoryRecord : THistoryRecord);
end;

TAlarmHistoryRecord = class(THistoryRecord)
  procedure Insert();
end;

implementation

{ THistory }

procedure THistory.Add(pHistoryRecord: THistoryRecord);
begin
  pHistoryRecord.Insert();
end;

{ TAlarmHistoryRecord }

procedure TAlarmHistoryRecord.Insert;
begin
  MessageDlg('Alarm History Record - Insert Method', mtInformation, [mbOK], 0);
end;

end.

Usage
procedure TForm1.Button1Click(Sender: TObject);
var
  lHistory : THistory;
  lHistoryRecord : TAlarmHistoryRecord;
begin

  lHistory := THistory.Create();

  lHistoryRecord := TAlarmHistoryRecord.Create();

  // I want this to call the TAlarmsHistoryRecord.Insert proc not the
  // HistoryRecord base class Insert proc.
  lHistory.Add(lHistoryRecord);

end;

2 个答案:

答案 0 :(得分:8)

您错过了覆盖

TAlarmHistoryRecord = class(THistoryRecord)
  procedure Insert(); override;
end;

答案 1 :(得分:6)

你错过了override方法声明中的TAlarmHistoryRecord指令,即它应该是

procedure Insert(); override;

实际上编译器应警告您该方法隐藏了一个继承的方法。