【问题标题】:Delphi Error: E2010 Incompatible types 'TRealFunction' and 'Procedure'Delphi 错误:E2010 不兼容的类型 'TRealFunction' 和 'Procedure'
【发布时间】:2018-07-11 08:25:57
【问题描述】:

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

我想计算函数评估的次数 (nfeval) 使用包装器在衍生产品的构造中使用 输入函数。但是编译器不喜欢我的实现, 显示此错误 E2010 不兼容的类型 'TRealFunction' 和 'Procedure'。

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

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 吗? 谢谢您的帮助!

【问题讨论】:

    标签: delphi


    【解决方案1】:

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

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

    文档:Anonymous Methods in Delphi

    【讨论】:

    • 这实际上适用于上述实现。但是,如果我的数值导数方法使用需要特定类型 TRealFunction 作为第一个输入的过程呢?像这样:函数 TFunctionWithDerivatives.NumFirstlDer(const x : Single) : Single;开始 NumericalFirstDerivative(objFunWrapper, x, 结果);结束;
    • 那么你有一个非常大的问题,因为你使用了一个带有变量捕获的匿名方法,并且变量捕获的上下文不能用问题中TRealFunction 的声明来表示。你了解什么是变量捕获吗?
    • > 不,现在正在寻找信息。
    • 我的回答有文档链接
    猜你喜欢
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 2011-12-22
    • 2013-06-09
    • 2021-03-02
    • 1970-01-01
    相关资源
    最近更新 更多