Inherited 应该如何用呢?我自己作了一个样本程序,这个样本里面如何体现 inherited 的作用呢?~(31分)

  • 主题发起人 主题发起人 yanyading
  • 开始时间 开始时间
Y

yanyading

Unregistered / Unconfirmed
GUEST, unregistred user!

我主要希望通过一个简单的程序学习如何用 inherited, 它具体可以起什么作用呢?这个程序好像有问题,运行不起~

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;

type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

type
TFather = class(TObject)
private
S1: Integer;
S2: Integer;
public
function Add(A1: Integer
A2: Integer): String;
end;

type
TChild = class(TFather)
public
function Hello(A1: Integer
A2: Integer): String;
end;

var
Form1: TForm1;
Father: TFather;
Child: TChild;

implementation

{$R *.dfm}

function TFather.Add(A1: Integer
A2: Integer): String;
begin
S1 := A1; // 故意转到 private 变量
S2 := A2; // 故意转到 private 变量
Result := IntToStr(S1 + S2);
end;

function TChild.Hello(A1: Integer
A2: Integer): String;
begin
inherited Add(A1, A2); // inherited 在这里!!!
Result := IntToStr(S1 + S2);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
Father := TFather.Create;
Child := Child.Create;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
Father.Free;
Child.Free;
end;

end.
 
Child :=TChild.Create;
 
type
TFather = class(TObject)
private
S1: Integer;
S2: Integer;
public
function Add(A1: Integer
A2: Integer): string;overload;
end;

type
TChild = class(TFather)
public
s3:string;
function ADD(A1: Integer): String;overload;
end;

var
Form1: TForm1;
Father: TFather;
Child: TChild;

implementation

{$R *.dfm}

function TFather.Add(A1: Integer
A2: Integer): String;
begin
S1 := A1;
S2 := A2;
Result := IntToStr(S1 + S2);
end;
function TChild.ADD(A1: Integer): String;
begin
s3:=inttostr(A1);
result:=inherited ADD(A1,A1);//A1=2,但结果仍为5
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Father := TFather.Create;
Child := tChild.Create();

end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
Father.Free;
Child.Free;

end;

procedure TForm1.Button1Click(Sender: TObject);
begin
label1.caption:=Child.add(2,3);
end;

end.
 
怎么没反应?你执行 Child.Hello(1,2) 难道不是返回'3'?
 
function TChild.Hello(A1: Integer
A2: Integer): String;
begin
//inherited Add(A1, A2); // 不需要inherited ,直接用下面的即可
Add(A1, A2);
Result := IntToStr(S1 + S2);
end;
 
后退
顶部