2012-12-19 28 views
2

我創建的類SerialForms.pas(17):W1010方法「創建」隱藏了基類型的虛擬方法TComponent「

FormInfo = class (TComponent) 
    private 
    FLeftValue : Integer; 
    FTopValue : Integer; 
    FHeightValue : Integer; 
    FWidthValue : Integer; 
    public 
    constructor Create(
     AOwner : TComponent; 
     leftvalue : integer; 
     topvalue : integer; 
     heightvalue : integer; 
     widthvalue : integer); 
    protected 
    procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; 
    function GetChildOwner: TComponent; override; 
    //procedure SetParentComponent(Value : TComponent); override; 
    published 
    property LeftValue : Integer read FLeftValue write FLeftValue; 
    property TopValue : Integer read FTopValue write FTopValue; 
    property HeightValue : Integer read FHeightValue write FHeightValue; 
    property WidthValue : Integer read FWidthValue write FWidthValue; 
    end; 

其進一步用於形式序列化。創建方法有以下實施

constructor FormInfo.Create(AOwner: TComponent; leftvalue, topvalue, heightvalue, 
    widthvalue: integer); 
begin 
    inherited Create(AOwner); 

    FLeftValue := leftvalue; 
    FTopValue := topvalue; 
    FHeightValue := heightvalue; 
    FWidthValue := widthvalue; 
end; 

作爲組裝的結果我收到警告

[dcc32 Warning] SerialForms.pas(17): W1010 Method 'Create' hides virtual method of base type 'TComponent' 

,需要什麼讓擺脫這一警告沒有應用的功能丟失?

+1

見,更具可讀性http://docwiki.embarcadero.com/RADStudio/XE3/en/W1010_Method_%27 %25s%27_hides_virtual_method_of_base_type_%27%25s%27_%28Delphi%29 – ain

+2

當您的表單從.dfm文件創建時,它會調用'TComponent'中引入的虛擬構造函數。當表單來自.dfm時,您的構造函數將不會被調用。如果你的構造函數創建了任何對象,那麼你會遇到問題。你的設計可能是錯誤的。 –

+2

要隱藏繼承的'TComponent'虛擬ctor是一個壞主意,如果你想讓額外的ctor使用不同的名稱,比如'CreatePos'。 – kludg

回答

6

使用reintroduce保留字,表示要有意隱藏基類的構造函數在類編譯:

TMyClass = class (TComponent) 
public 
    constructor Create(AOwner: TComponent; MyParam: Integer; Other: Boolean); reintroduce; 

這樣,不會顯示警告。

這就是說,你必須重新考慮隱藏TComponent.Create構造函數。這是一個壞主意,因爲在設計時添加到窗體/數據模塊時,Delphi會調用默認的TComponent.Constructor以在運行時創建組件實例。

TComponent使構造函數爲虛擬以允許您在該過程中執行自定義代碼,但是您必須堅持Create企業只傳遞所有者,並讓流機制在創建後處理存儲的屬性值做完了。

如果是這種情況,您的組件必須支持「未配置」,或者在此通用構造函數中爲其屬性設置默認值。

您可以使用不同的名稱提供更多的構造函數,以允許您在運行時從代碼傳遞值爲不同的屬性值創建實例,以方便您使用。

+0

重新引入中斷多態性。這意味着您不能再使用元類(TxxxClass = Tyyy類)來實例化您的TComponent後代,因爲其Create不會被調用。另請參閱:http://stackoverflow.com/questions/53806/reintroducing-functions-in-delphi –

+0

@Marjan您仍然可以使用元類和虛構造器創建實例。恕我直言,有能力隱藏一個虛擬構造函數只是你手頭上的一個工具,並可能會在一段時間有用。我不記得我什麼時候用過它,或者我曾經做過一次。我不反對它,但它看起來像我也不使用它。 – jachguate

+0

是的,你可以,但我真的沒有看到使用隱藏你可以訪問的東西。我更喜歡爲這種事先創建一個明確命名的構造函數(即'CreateWith'),它首先調用標準構造函數(沒有繼承)。 –

1

它可能會更好 - 如果你使用一個不同的名稱爲您的構造函數,如

constructor FormInfo.CreateWithSize(AOwner: TComponent; leftvalue, topvalue, heightvalue, widthvalue: integer);