Delphi 属性重写

Delphi 属性重写,delphi,Delphi,我有一个从TParent派生的类TChild。TParent有一个属性MyProp,用于读取和设置数组中的某些值。当然,这个属性是由TChild继承的,但是我想在child的属性中添加一些额外的处理。下面的代码更好地解释了我想做什么,但它不起作用。我如何实现它 TParent = class... private function getStuff(index: integer): integer; virtual; procedure setStuff(index: integ

我有一个从TParent派生的类TChild。TParent有一个属性MyProp,用于读取和设置数组中的某些值。当然,这个属性是由TChild继承的,但是我想在child的属性中添加一些额外的处理。下面的代码更好地解释了我想做什么,但它不起作用。我如何实现它

TParent = class...
 private
   function  getStuff(index: integer): integer; virtual;
   procedure setStuff(index: integer; value: integer); virtual;
 public
   property MyProp[index: integer] read GetStuff write SetStuff
 end;

TChild = class...
 private
   procedure setStuff(index: integer; value: integer); override;
   function  getStuff(index: integer): integer; override;
 public
   property MyProp[index: integer] read GetStuff write SetStuff
 end;

procedure TChild.setStuff(value: integer);
begin
 inherited;      //  <-- execute parent 's code and
 DoMoreStuff;    //  <-- do some extra suff
end;

function TChild.getStuff;
begin
 result:= inherited;   <---- problem was here   
end;
tpart=class。。。
私有的
函数getStuff(索引:整数):整数;事实上的
过程setStuff(索引:整数;值:整数);事实上的
公众的
属性MyProp[index:integer]读取GetStuff写入SetStuff
结束;
TChild=类。。。
私有的
过程setStuff(索引:整数;值:整数);推翻
函数getStuff(索引:整数):整数;推翻
公众的
属性MyProp[index:integer]读取GetStuff写入SetStuff
结束;
程序TChild.setStuff(值:整数);
开始

继承的;// 我对德尔福很生疏。你正在经历什么样的“它不起作用”?它是否无法编译

我怀疑继承的调用不会编译,因为父级实际上没有执行的方法。

。 子函数的实现是错误的。基本上,代码是有效的。 解决办法是:

Result := inherited getStuff(Index);

您不必重新申报属性。只需重写getter和setter方法,您就可以了。为了让这对其他人有所帮助,您可能应该说什么是错误的。我猜你指的是
private
而不是“protected”?不,Smasher,问题出在TChild.GetStuff中,它试图像函数一样使用bare
inherted
。德尔福不允许这样。如果要将
继承的
用作函数,则需要指定函数名和参数。此外,在这种情况下,私有不会有任何效果,因为两个类显然位于同一个单元中。如果它们位于不同的单元中,那么子类将无法编译,因为它无法访问祖先类的私有虚拟方法。(这与C++不同,在这里允许您重写私有方法,即使您不允许调用它们。)