2009-12-17 157 views
2

我有一个从TParent派生的TChild类。 TParent有一个MyProp属性,它读取和设置数组中的一些值。当然这个属性是由TChild继承的,但是我想在儿童属性中添加一些额外的处理。下面的代码更好地解释了我想要做的事情,但它不起作用。我怎样才能实现它?属性覆盖

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; 
+2

您不必重新声明属性。只要重写getter和setter方法,你就会好起来的。 – jpfollenius 2009-12-17 18:58:07

+0

@Smasher - 对。谢谢。 – Ampere 2009-12-17 21:02:37

回答

2

已解决。 子函数的实现是错误的。基本上,该代码的作品。 解决方案是:

Result := inherited getStuff(Index); 
+0

为了让他人对你有所帮助,你应该说出了什么问题。我想你的意思是“私人”而不是“保护”? – jpfollenius 2009-12-17 18:59:12

+1

不,粉碎机,问题出在TChild.GetStuff上,它试图像一个函数一样使用''inherted''。德尔福不允许这样做。如果要将'inherited'用作函数,则需要指定函数名称和参数。 – 2009-12-17 19:35:32

+0

除此之外,在这种情况下私人不会产生效果,因为两个班级显然是在同一单位。如果它们在不同的单元中,那么后代类将不会编译,因为它不能访问祖先类的私有虚拟方法。 (这与C++不同,即使您不允许调用它们,也可以重写私有方法。) – 2009-12-17 19:37:25

0

我对Delphi很生疏。你遇到什么样的“它不工作”?它没有编译?

我怀疑inherited调用不会编译,因为父类没有真正的方法来执行。