2009-12-17 156 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調用不會編譯,因爲父類沒有真正的方法來執行。