Advertisement
Guest User

Enumeratos/Override/Forward declared class

a guest
Mar 21st, 2014
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 1.70 KB | None | 0 0
  1. program project1;
  2.  
  3. uses
  4.   Classes;
  5.  
  6. type
  7.   TFoo = class;
  8.   TBar = class;
  9.  
  10.   TFooListEnumerator = class
  11.   private
  12.     FFooList: TList;
  13.     FCurrentIndex: Integer;
  14.   protected
  15.     function GetCurrent: TFoo; virtual;
  16.   public
  17.     constructor Create(AList: TList);
  18.     function MoveNext: boolean;
  19.     property Current: TFoo read GetCurrent;
  20.   end;
  21.  
  22.   { TBarListEnumerator }
  23.  
  24.   TBarListEnumerator = class(TFooListEnumerator)
  25.   protected
  26.     function GetCurrent: TBar; override;
  27.     // ^-- Fails with: Error: There is no method in an ancestor class to be overridden: "TBarListEnumerator.GetCurrent:TBar;"
  28.   public
  29.     property Current: TBar read GetCurrent;
  30.   end;
  31.  
  32.   { TBarList }
  33.  
  34.   TBarList = class(TList)
  35.   public
  36.     function GetEnumerator: TBarListEnumerator;
  37.   end;
  38.  
  39.   TFoo = class
  40.   public
  41.     Val: Integer;
  42.   end;
  43.  
  44.   TBar = class(TFoo)
  45.   public
  46.     Val2: Integer;
  47.   end;
  48.  
  49. { TFooListEnumerator }
  50.  
  51. function TFooListEnumerator.GetCurrent: TFoo;
  52. begin
  53.   result := TFoo(FFooList[FCurrentIndex]);
  54. end;
  55.  
  56. constructor TFooListEnumerator.Create(AList: TList);
  57. begin
  58.   FFooList := AList;
  59.   FCurrentIndex := -1;
  60. end;
  61.  
  62. function TFooListEnumerator.MoveNext: boolean;
  63. begin
  64.   inc(FCurrentIndex);
  65.   result := FCurrentIndex < FFooList.Count;
  66. end;
  67.  
  68. { TBarListEnumerator }
  69.  
  70. function TBarListEnumerator.GetCurrent: TBar;
  71. begin
  72.   result := TBar(inherited GetCurrent);
  73. end;
  74.  
  75. { TBarList }
  76.  
  77. function TBarList.GetEnumerator: TBarListEnumerator;
  78. begin
  79.   result := TBarListEnumerator.Create(Self);
  80. end;
  81.  
  82. var
  83.   BarList: TBarList;
  84.   Bar: TBar;
  85.  
  86. begin
  87.   BarList := TBarList.Create;
  88.   BarList.Add(TFoo.Create);
  89.  
  90.   for Bar in BarList do
  91.     Bar.Val2 := 1;
  92.  
  93.   BarList.Free;
  94. end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement