Delphi: Understanding constructors

后端 未结 4 1543
有刺的猬
有刺的猬 2020-11-30 23:28

i\'m looking to understand

  • virtual
  • override
  • overload
  • reintroduce

when applied to object constructors. Every

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 00:15

    This is a working implementation of the definitions wanted:

    program OnConstructors;
    
    {$APPTYPE CONSOLE}
    
    uses
      SysUtils;
    
    type
    
    TComputer = class(TObject)
    public
        constructor Create(Cup: Integer); virtual;
    end;
    
    TCellPhone = class(TComputer)
    public
        constructor Create(Cup: Integer; Teapot: string); reintroduce; overload; virtual;
    end;
    
    TiPhone = class(TCellPhone)
    public
        constructor Create(Cup: Integer); overload; override;
        constructor Create(Cup: Integer; Teapot: string); override;
    end;
    
    { TComputer }
    
    constructor TComputer.Create(Cup: Integer);
    begin
      Writeln('Computer: cup = ', Cup);
    end;
    
    { TCellPhone }
    
    constructor TCellPhone.Create(Cup: Integer; Teapot: string);
    begin
      inherited Create(Cup);
      Writeln('Cellphone: teapot = ', Teapot);
    end;
    
    { TiPhone }
    
    constructor TiPhone.Create(Cup: Integer);
    begin
      inherited Create(Cup);
      Writeln('iPhone: cup = ', Cup);
    end;
    
    constructor TiPhone.Create(Cup: Integer; Teapot: string);
    begin
      inherited;
      Writeln('iPhone: teapot = ', Teapot);
    end;
    
    var
      C: TComputer;
    
    begin
    
      C := TComputer.Create(1);
      Writeln; FreeAndNil(C);
    
      C := TCellPhone.Create(2);
      Writeln; FreeAndNil(C);
      C := TCellPhone.Create(3, 'kettle');
      Writeln; FreeAndNil(C);
    
      C := TiPhone.Create(4);
      Writeln; FreeAndNil(C);
      C := TiPhone.Create(5, 'iPot');
    
      Readln; FreeAndNil(C);
    
      end.
    

    with results:

    Computer: cup = 1
    
    Computer: cup = 2
    
    Computer: cup = 3
    Cellphone: teapot = kettle
    
    Computer: cup = 4
    iPhone: cup = 4
    
    Computer: cup = 5
    Cellphone: teapot = iPot
    iPhone: teapot = iPot
    

    The first part is in accordance with this. The definition of the TiPhone two constructors then proceeds as follows:

    • The first constructor is overloading one of the two constructors inherited and overriding its sibling. To achieve this, use overload; override to overload the TCellPhone one while overriding the other constructor.
    • That being done, the second constructor needs a simple override to override its sibling.

提交回复
热议问题