Delphi typcast tlist项目C ++方法

时间:2013-03-20 22:19:45

标签: c++ delphi inheritance casting tlist

嗨,我有一个关于某些类型铸造方法的问题。我正在将一些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;

这是两个基础classe TBaseItem和TBaseClass。所以这里声明了新的类TchildItem,它来自TBaseItem和TChildClass,它是从TBaseClass派生的。 TChildItem是覆盖方法SomeMethod,更重要的是TChildtClass以现在我们返回TBaseItem的TParentItem项的方式重写属性Items。

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;

通过这个例子,我想展示如何轻松地派生类和覆盖属性。从列表中获取正确类型的项目只需通过调用parent(base)属性Item并将其强制转换为正确的类型来完成。这是delphi apporach。

我想知道如何将这部分代码翻译成C ++。目前我声明了一个新的基类,它不是从任何类派生的,它有公共var项

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方法进入错误的方向。

你有什么建议?我该怎么做?

非常感谢你!

1 个答案:

答案 0 :(得分:5)

Delphi代码是旧的和早期的泛型,Delphi类似于C ++模板。在现代Delphi代码中,那些列表类根本就不存在。相反,人们会使用TList<TBaseItem>TList<TChildItem>

在C ++代码中,您只需使用vector<TBaseItem*>vector<TChildItem*>。您的C ++翻译中没有必要实现TBaseClassTChildClass

我也会纠正你的术语。 Delphi属性无法覆盖。 TChildClass中的新属性就是新属性。

相关问题