【问题标题】:Delphi typcast tlist items C++ approachDelphi typcast tlist 项 C++ 方法
【发布时间】: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


【解决方案1】:

Delphi 代码是旧的并且早于泛型,Delphi 类似于 C++ 模板。在现代 Delphi 代码中,这些列表类根本不存在。相反,人们会使用TList&lt;TBaseItem&gt;TList&lt;TChildItem&gt;

在 C++ 代码中,您只需使用 vector&lt;TBaseItem*&gt;vector&lt;TChildItem*&gt;。你的 C++ 翻译根本没有意义来实现 TBaseClassTChildClass

我也会更正您的术语。 Delphi 属性不能被覆盖。 TChildClass 中的新属性就是这样,一个新属性。

【讨论】:

  • 是的,我认为会是这样。我只是不确定。感谢您的解释。
  • 我脑海中闪过一件事。我想有一些 item 的基类,所有其他类都是从它派生的。比如说 CShape 类,然后我派生 CRectangle、CCircle...
  • 您可以轻松完成所有这些事情。我的观点是,您问题中的 Delphi 容器类纯粹是由于旧 Delphi 版本的限制。拥有 C++ 标准库时不存在的限制。
  • 我脑海中闪过一件事。我想有一些 item 的基类,所有其他类都是从它派生的。比如说 CShape 类,然后我派生 CRectangle、CCircle ......所以如果我使用多态......我可能应该声明 vector Shapes;然后我可以向它添加不同的类型并从中获取它?
  • 是的,这听起来很合理。如果您希望容器接受 CShape 的任何子类,那么这就是您需要做的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-06
  • 2021-10-13
相关资源
最近更新 更多