2012-07-11 32 views
1

繼承我有一個從TCollection繼承一個類的類itemClass時(可以稱之爲「TMyCollection」),我不得不從它繼承一個新的類(可以稱之爲「TMyItems」)如何改變從TCollection

通常我們在TCollection的構造函數中傳遞ItemClass類型,但在我的情況下,TMyCollection的構造函數被新的構造函數覆蓋,該構造函數不帶ItemClass,它只接受Owner。

如果繼承的構造函數不接受ItemClass參數,我需要知道如何更改「TMyItems」中的ItemClass。

問候。

回答

1

你仍然可以從子類中調用繼承TCollection.Create,即使它不具有相同的簽名:

TMyCollectionItem = class(TCollectionItem) 
    private 
    FIntProp: Integer; 
    procedure SetIntProp(const Value: Integer); 
    public 
    property IntProp: Integer read FIntProp write SetIntProp; 
    end; 

    TMyCollection = class(TCollection) 
    public 
    constructor Create(AOwner: TComponent);virtual; 
    end; 

{ TMyCollection } 

constructor TMyCollection.Create(AOwner: TComponent); 
begin 
    inherited Create(TMyCollectionItem); // call inherited constructor 
end; 

編輯

按照樓主的意見,「訣竅」是將新構造函數標記爲重載。由於它是一個重載,它不隱藏對TCollection構造函數的訪問。

TMyCollection = class(TCollection) 
    public 
    constructor Create(AOwner: TComponent);overload; virtual; 
    end; 

    TMyItem = class(TCollectionItem) 
    private 
    FInt: Integer; 
    public 
    property Int: Integer read FInt; 
    end; 

    TMyItems = class(TMyCollection) 
    public 
    constructor Create(AOwner: TComponent);override; 
    end; 

implementation 

{ TMyCollection } 

constructor TMyCollection.Create(AOwner: TComponent); 
begin 
    inherited Create(TCollectionItem); 

end; 

{ TMyItems } 

constructor TMyItems.Create(AOwner: TComponent); 
begin 
    inherited Create(TMyItem); 
    inherited Create(AOwner); // odd, but valid 
end; 

end. 
+0

的問題是,我有2級繼承 的代碼是這樣的: TMyCollection =類(TCollection).... TMyCollection的構造是 構造創建(AOwner: TComponent); (TMoCollection) TMyItems的構造函數: 構造函數Create(AOwner:TComponent); 當試圖調用TMyItems中的繼承構造函數時,它將調用TMyCollection的構造函數,這不是我想要的,因爲我有一個新的ItemClass並且它必須傳遞給集合... – user1512094 2012-07-11 09:29:38

+0

New ItemClass也從TMyCollectionItem繼承它將擁有所有屬性和事件TMyCollectionItem – user1512094 2012-07-11 09:34:36