【发布时间】:2013-03-10 06:37:57
【问题描述】:
您好,我有一个关于某些类型转换方法的问题。我正在将一些 Delphi 文件翻译成 C++。我有从 TList 派生的类的 delphi 声明,它是其他派生类的基类。
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。所以这里声明了从 TBaseItem 派生的新类 TchildItem 和从 TBaseClass 派生的 TChildClass。 TChildItem 覆盖了 SomeMethod 方法,更重要的是 TChildtClass 覆盖了属性 Items,现在我们正在返回 TParentItem 中的 TBaseItem 项。
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;
通过这个例子,我想展示派生类和覆盖属性是多么容易。从列表中获取正确类型的项目只需调用父(基)属性 Item 并将其类型转换为正确类型即可。这是德尔福方法。
我想知道如何将这部分代码翻译成 C++。目前我声明了一个新的基类,它不是从任何类派生的,它有 public var Items 这是
class TBaseItem{
virtual void SomeMethod();
}
class TBaseClass {
public:
vector<TBaseItem> Items;
};
class TChildItem : public TBaseItem{
}
class TChildClass : public TBaseClass {
};
然后使用
return (TChildItem) Items[Idx]
这意味着我想访问父级 (TBaseClass) 的公共变量,例如向量项并将其类型转换为正确的类型...我的第一印象是,我可能会在使用 Delphi 方法时走错方向。
你有什么建议?我该怎么办?
非常感谢!
【问题讨论】:
-
试图将一种语言的“良好实践”应用到另一种语言中几乎总是一个坏主意,尤其是当语言差异如此之大时。我真的不明白你想要做什么,但如果你只是想创建某种具有不同可能类型元素的容器,请尝试查看模板。
标签: c++ delphi inheritance casting tlist