如何定义子类中参数不同的虚函数?

时间:2013-03-27 23:13:02

标签: delphi polymorphism

我想要一个 复制在基类中定义为虚拟的例程,稍后在派生类中实现。 问题是由于参数不同,不允许覆盖该过程。 有没有使用Delphi的类模型的解决方案,还是我的方法完全错了?

type
  TCar = class
    procedure CopyFrom(c: TCar); virtual;
  end;

  TChrysler = class(TCar)
    FColor: Integer;
    procedure CopyFrom(c: TChrysler); override;
  end;

procedure TCar.CopyFrom(c: TCar);
begin
  //virtual
end;

procedure TChrysler.CopyFrom(c: TCrysler);
begin
  FColor := c.FColor;
end;

var
  Car1, Car2: TCar;
begin
  Car1 := TChrysler.Create;
  Car2 := TChrysler.Create;

  Car2.CopyFrom(Car1); //TChrysler.CopyFrom should be called.
end;

1 个答案:

答案 0 :(得分:5)

您需要保持参数列表相同,只需在实现中进行类型检查:

type
  TCar = class
    procedure CopyFrom(c: TCar); virtual;
  end;

  TChrysler = class(TCar)
    FColor: Integer;
    procedure CopyFrom(c: TCar); override;
  end;

procedure TCar.CopyFrom(c: TCar);
begin
  //virtual
end;

procedure TChrysler.CopyFrom(c: TCar);
begin
  if c is TCrysler then
    FColor := TCrysler(c).FColor;
  inherited;
end;