关于回调函数中被调用函数的范围(50分)

  • 主题发起人 主题发起人 sunrain_114
  • 开始时间 开始时间
S

sunrain_114

Unregistered / Unconfirmed
GUEST, unregistred user!
type
TmyFunc = function (x:Integer):Integer;
TmyPro = procedure;
……
public
{ Public declarations }
//function Func1(x:Integer):Integer;
// procedure myShow;
end;

function MyFun(aFun:TmyFunc;x:Integer):Integer;

implementation

{$R *.dfm}
function MyFun(aFun: TmyFunc
x: Integer): Integer;
begin
result := aFun(x);
end;

function Func1(x: Integer): Integer;
begin
result := x * 2 ;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage('Fun1 : '+IntToStr(myfun(Func1,5)));
end;

procedure myShow;
begin
showmessage('aaa');
end;

procedure TForm1.Button2Click(Sender: TObject);
var
aPro : TmyPro;
begin
aPro := myShow;
aPro;
end;

我在button1与button2点击事件中调用的函数myFun与过程myshow,两者如果被声明为本窗体的局部函数与过程,编译不能通过,把声明从窗体类中移出,成为一个全局函数与过程,则可以正常使用。
为什么会这样? 求教?
 
type
TmyFunc = function (x:Integer):Integer of object;
TmyPro = procedure of object;
...
function TForm1.Func1(x: Integer): Integer;
...
procedure TForm1.myShow;
...
 
回调函数要求是一个函数指针。如果把要回调的函数放在类里就变成了类方法,类方法在调用时隐含Self指针,所以不符合回调规范。如果你在调用时修正调用堆践也是可以,不过你要对系统底层比较了解才行。(Delphi里有现成的实现)
 
unit Unit1;

interface

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

type
TmyFun1 = function(x: integer): integer;
TmyPro1 = procedure;

TmyFun2 = function(x: Integer): Integer of object;
TmyPro2 = procedure of object;


TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
{ Private declarations }
function Func2(x: Integer): Integer;
procedure myShow2;
function MYFun2(aFun: TmyFun2
x: integer): integer;
public
{ Public declarations }
end;

var
Form1: TForm1;

function MYFun1(aFun: TmyFun1
x: integer): integer;
implementation

{$R *.dfm}

function MYFun1(aFun: TmyFun1
x: integer): integer;
begin
result := aFun(x);
end;


function Func1(x: Integer): Integer;
begin
result := x * 2;
end;

procedure myShow1;
begin
showmessage('show1111111');
end;


function TForm1.MYFun2(aFun: TmyFun2
x: integer): integer;
begin
result := afun(x);
end;

function TForm1.Func2(x: Integer): Integer;
begin
x := x + 2;
end;

procedure TForm1.myShow2;
begin
showmessage('show22222222');
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
showmessage('aFun1=' + inttostr(myFun1(func1, 2)));
end;

procedure TForm1.Button2Click(Sender: TObject);
var p: tmypro1;
begin
p := myshow1;
p;
end;


procedure TForm1.Button3Click(Sender: TObject);
var p: tmypro2;
begin
p := myshow2;
p;
end;

procedure TForm1.Button4Click(Sender: TObject);
begin
showmessage('fun2=' + inttostr(MYFun2(Func2, 10)));
end;

end.

----------button4 还是不对阿!
 
回调函数就是这样的特性
 
接受答案了.
 
后退
顶部