2013-03-20 54 views
1

嗨我有一個關於某些類型鑄造方法的問題。我正在將一些Delphi文件翻譯成C++。我有從TList派生的類的delphi聲明,它是其他派生類的基類。德爾福typcast tlist項目C++方法

type TBaseItem = class (TObject) 
public 
    procedure SomeProcedure; virtual; abstract; 
end; 

Type TBaseClass = class(TList) 
private 
    function GetItem(Index: Integer): TBaseItem; 
    procedure SetItem(Value: TBaseItem; Index: Integer); 
public 
    property Items[Index: Integer]: TBaseItem read GetItem write SetItem; 
end; 


function TBaseClass.GetItem(Index: Integer): TBaseItem; 
begin 
    Result := TBaseItem(inherited Items[Index]); 
end; 

procedure TBaseClass.SetItem(Value: TBaseItem; Index: Integer); 
begin 
    inherited Items[Index] := Value; 
end; 

這是TBaseItem和TBaseClass的兩個基類。所以這裏聲明的新類TchildItem是從TBaseItem派生而來的,TChildClass派生自TBaseClass。 TChildItem重寫SomeMethod方法,更重要的是TChildtClass以重寫屬性Items的方式,現在我們返回的是TBaseItem的TParentItem項目。

type TChildItem = class (TBaseItem) 
public 
    procedure SomeProcedure; override; 
end; 

type TChildClass = class(TBaseClass) 
private 
    function GetItem(Index: Integer): TChildItem; 
    procedure SetItem(Value: TChildItem; Index: Integer); 
public 
    property Items[Index: Integer]: TChildItemread GetItem write SetItem; 
end; 

function TChildClass .GetItem(Index: Integer): TChildItem; 
begin 
    Result := TChildItem(inherited Items[Index]); 
end; 

procedure TChildClass.SetItem(Value: TChildItem; Index: Integer); 
begin 
    inherited Items[Index] := Value; 
end; 

在這個例子中,我想要展示派生類和重寫屬性是多麼容易。從列表中獲取適當類型的項目只需調用父項(基本)屬性項並將其轉換爲適當的類型即可。這是delphi apporach。

我不知道如何將這部分代碼翻譯成C++。目前,我宣佈這是不是從任何類派生的新的基類,它具有公共變種項目是

class TBaseItem{ 
    virtual void SomeMethod(); 
} 

class TBaseClass { 
public: 
    vector<TBaseItem> Items; 
}; 


class TChildItem : public TBaseItem{ 
} 

class TChildClass : public TBaseClass { 
}; 

然後用

return (TChildItem) Items[Idx] 

這意味着我想訪問父母(TBaseClass)公共變量,如該向量Items,並將它轉換爲適當的類型......我的第一印象是,我可能會用Delphi方法進入錯誤的方向。

你有什麼建議?我應該怎麼去?

非常感謝!

+1

試圖將一種語言的「良好實踐」應用於另一種語言,幾乎總是一個壞主意,特別是當語言差異很大時。我並沒有真正明白你想要做什麼,但是如果你只是想創建一種具有不同可能類型元素的容器,可以試着看一下模板。 – PlasmaHH 2013-03-20 22:35:47

回答

5

德爾福的代碼是舊的和預日期泛型,Delphi模擬C++模板。在現代的Delphi代碼中,這些列表類將不存在。相反,人們會使用TList<TBaseItem>TList<TChildItem>

在C++代碼中,您只需使用vector<TBaseItem*>vector<TChildItem*>。您的C++翻譯根本沒有意義實現TBaseClassTChildClass

我也會糾正你的術語。 Delphi屬性不能被重寫。 TChildClass中的新房產就是這樣一個新房產。

+0

是的,我認爲它會如此。我只是無法確定。 Thanx解釋。 – Nix 2013-03-20 23:26:41

+0

有一件事讓我想起了。我想有一些項目的基類,所有其他類都從它派生。比方說,例如類CShape,然後我派生CRectangle,CCircle ... – Nix 2013-03-21 08:22:44

+0

你可以很容易地完成所有這些事情。我的觀點是,你的問題中的Delphi容器類純粹是由於舊的Delphi版本的限制。當你擁有C++標準庫時,這些限制是不存在的。 – 2013-03-21 08:27:12