4

我想有一个复制例程,它在基类中定义为虚拟,稍后在派生类中实现。问题是由于参数不同,不允许覆盖该过程。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;
4

1 回答 1

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;
于 2013-03-27T23:37:29.623 回答