zoukankan      html  css  js  c++  java
  • 覆盖虚方法

    unit Unit1;
    
    interface
    
    uses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs;
    
    type
      TForm1 = class(TForm)
        procedure FormCreate(Sender: TObject);
      private
        { Private declarations }
      public
        { Public declarations }
      end;
    
    //夫类
      TParent = class
      protected
        function MyFun(i: Integer): Integer; dynamic;  //动态方法
        procedure MyProc; virtual;  //虚方法
      end;
    
    //子类
      TChild = class(TParent)
      protected
        function MyFun(i: Integer): Integer; override;  //覆盖
        procedure MyProc; override;  //覆盖
      end;
    
    var
      Form1: TForm1;
    
    implementation
    
    {$R *.dfm}
    
    { TParent }
    
    function TParent.MyFun(i: Integer): Integer;
    begin
      Inc(i);
      Result := i;
    end;
    
    procedure TParent.MyProc;
    begin
      ShowMessage('Parent');
    end;
    
    { TChild }
    
    function TChild.MyFun(i: Integer): Integer;
    begin
      i := inherited MyFun(i);  //先调用夫类方法,被 +1;当然可以不调用
      Inc(i);                   //子类再 +1
      Result := i;
    end;
    
    procedure TChild.MyProc;
    begin
      inherited;  //先调用夫类方法;当然可以不调用
      ShowMessage('Child');
    end;
    
    //测试
    procedure TForm1.FormCreate(Sender: TObject);
    var
      p: TParent;
      c: TChild;
    begin
      p := TParent.Create;
      c := TChild.Create;
    
      p.MyProc;  //Parent
      c.MyProc;  //Parent; TChild
    
      ShowMessage(IntToStr(p.MyFun(2)));  //3
      ShowMessage(IntToStr(c.MyFun(2)));  //4
    
      p.Free;
      c.Free;
    end;
    
    end.
    
  • 相关阅读:
    1063. Set Similarity
    A1047. Student List for Course
    A1039. Course List for Student
    最大公约数、素数、分数运算、超长整数计算总结
    A1024. Palindromic Number
    A1023. Have Fun with Numbers
    A1059. Prime Factors
    A1096. Consecutive Factors
    A1078. Hashing
    A1015. Reversible Primes
  • 原文地址:https://www.cnblogs.com/del/p/983657.html
Copyright © 2011-2022 走看看