繁体   English   中英

Delphi错误:E2010不兼容的类型'TRealFunction'和'Procedure'

[英]Delphi Error: E2010 Incompatible types 'TRealFunction' and 'Procedure'

我正在设计一个类(TFunctionWithDerivatives),其类具有计算输入函数f的数值导数的方法:x \\ in R->R。

我想说明在输入函数上使用包装器构造导数时使用的函数评估(nfeval)的数量。 但是编译器不喜欢我的实现,显示此错误E2010不兼容类型'TRealFunction'和'Procedure'。

这是一个简化的代码,其中在Tform1.Create中创建了TFunctionWithDerivatives的实例。

unit Unit2;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, 
  System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs;

type TRealFunction = function(const x : Single) : Single;

type TFunctionWithDerivatives = class

   objfun : TRealFunction;
   nfeval : Integer;

   constructor Create(const _objfun : TRealFunction);
   function NumFirstlDer(const x : Single) : Single;

   private
   objFunWrapper : TRealFunction;

end;

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

var
  Form1: TForm1;

implementation

{$R *.dfm}

function F1(const x : Single) : Single;
begin
  RESULT := sqr(x);
end;

procedure TForm1.Create(Sender: TObject);
var FWD    : TFunctionWithDerivatives;
begin
   FWD := TFunctionWithDerivatives.create(F1);
end;


// begin methods of TFunctionWithDerivatives
     constructor TFunctionWithDerivatives.Create(const _objfun : TRealFunction);
     begin
        inherited create;
        nfeval := 0;
        objFun := _objfun;
        objFunWrapper := function(const x : Single) : Single
                         begin
                           RESULT := objFun(x);
                           Inc(nfeval);
                         end;
     end;

     function TFunctionWithDerivatives.NumFirstlDer(const x : Single) : Single;
     var h : Single;
     begin
       h:=1e-3;
       // RESULT := (objfun(x+h, Param) - objfun(x, Param)) / h ;
       RESULT := ( objFunWrapper(x+h) - objFunWrapper(x) ) / h;
     end;
// end methods of TFunctionWithDerivatives

end.

您知道如何在类内部定义objFunWrapper吗? 谢谢您的帮助!

您正在声明匿名方法。 要声明匹配的类型,必须使用reference to语法的reference to

type 
  TRealFunction = reference to function(const x: Single): Single;

文档: Delphi中的匿名方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM