如何声明两个相互关联的类?

问题描述 投票:5回答:3

我有一个与this类似的问题,但在delphi中。

type
  TThreadPopulator = class(TThread)
  private
    _owner:TASyncPopulator; //Undeclared identifier
  end;

type
  TAsyncPopulator = class
  private
    _updater: TThreadPopulator;
  end;

提到的问题的解决方案不适用于delphi

delphi delphi-xe2
3个回答
12
投票

请参见Forward Declarations and Mutually Dependent Classes文档。

Forward Declarations and Mutually Dependent Classes

使用消息来源,卢克!您的Delphi安装具有完整的VCL和RTL源,供您阅读,观看和学习。而且它经常使用此模板。每当您问自己“我该怎么做”时,只需考虑一下“ Borland是如何做到的”,并很有可能已经可以在Delphi提供的资源中获得现成的示例。


3
投票

在任何类定义之前使用此。转发类可在Delphi 2010中使用。我不知道您拥有的Delphi的女巫版本,但这是我可以考虑的唯一解决方案。

type (* start type section - one unified section "to rule them all" *)
  TAsyncPopulator = class; (* forward declaration *)

  TThreadPopulator = class(TThread)
  private
    _owner:TASyncPopulator;
  end;

  TAsyncPopulator = class (* final declaration - WITHIN that very section where forward declaration was made *)
  private
    _updater: TThreadPopulator;
  end;

希望我有所帮助


0
投票

除了使用前向声明,您还可以创建一个子类来解决此问题:

type   
 TAsyncPopulator = Class;
© www.soinside.com 2019 - 2024. All rights reserved.