2013-03-20 55 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