gpt4 book ai didi

delphi - 如何定义其参数在后代类中不同的虚函数?

转载 作者:行者123 更新时间:2023-12-03 15:27:19 26 4
gpt4 key购买 nike

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

最佳答案

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

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;

关于delphi - 如何定义其参数在后代类中不同的虚函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15671343/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com