Delphi: Method 'Create' hides virtual method of base - but it's right there

后端 未结 2 1966
广开言路
广开言路 2020-12-06 16:01

Consider the hypothetical object hierarchy, starting with:

TFruit = class(TObject)
public
    constructor Create(Color: TColor); virtual;
end;
<
相关标签:
2条回答
  • 2020-12-06 16:35

    Two solutions:

    type
      TFruit = class(TObject)
      public
        constructor Create(Color: TColor); virtual;
      end;
    
      TApple = class(TFruit)
      public
        constructor Create(); reintroduce; overload;
        constructor Create(Color: TColor); overload; override;
      end;
    

    Or:

    type
      TFruit = class(TObject)
      public
        constructor Create; overload; virtual; abstract;
        constructor Create(Color: TColor); overload; virtual;
      end;
    
      TApple = class(TFruit)
      public
        constructor Create(); override;
        constructor Create(Color: TColor); override; 
      end;
    
    0 讨论(0)
  • 2020-12-06 16:45

    This appears to be a "which came first" sort of issue. (It appears NGLN found a solution.)

    There's another solution, also. You can use a default parameter:

    interface
    
    type
      TFruit=class(TObject)
      public
        constructor Create(Color: TColor); virtual;
      end;
    
      TApple=class(TFruit)
      public
        constructor Create(Color: TColor = clRed); override;
      end;
    
    implementation
    
    { TFruit }
    
    constructor TFruit.Create(Color: TColor);
    begin
      inherited Create;
    end;
    
    { TApple }
    
    constructor TApple.Create(Color: TColor);
    begin
      inherited;
    end;
    
    // Test code
    var
      AppleOne, AppleTwo: TApple;
    begin
      AppleOne := TApple.Create;
      AppleTwo := TApple.Create(clGreen);
    end;
    
    0 讨论(0)
提交回复
热议问题