一个类应使用功能指针调用另一类的方法

one class should invoke method of another class using a function pointer

本文关键字:调用 方法 指针 一类 一个 功能      更新时间:2023-10-16

我有咨询(免责声明):

  • 类成员功能指针
  • 通过功能指针调用C 类方法
  • C :功能指针到另一个类功能

为了说明我的问题,我将使用此代码(更新)

#include <iostream>
#include <cmath>
#include <functional>

class Solver{
public:
    int Optimize(const std::function<double(double,double>& function_to_optimize),double start_val, double &opt_val){
        opt_val = function_to_optimize(start_val);
        return 0;
    }
};
class FunctionExample{
public:
    double Value(double x,double y)
    {
        return x+y;
    }
};
int main(){
    FunctionExample F =FunctionExample();
    Solver MySolver=Solver();
    double global_opt=0.0;
    MySolver.Optimize(std::bind(&FunctionExample::Value, &F, std::placeholders::_2),1,global_opt);
    return 0;
}

有没有办法将该方法称为"值"?我没有问题要调用功能(没有类)

typedef double (*FunctionValuePtr)(double x);

,但这对我上面的示例没有帮助。我需要明确的方法名称。大多数示例使用静态方法。我无法使用静态方法。

您可以使用stl的<functional>标头:

double Gradient(const std::function<double(double)>& func, double y)
{
    const double h = 1e-5;
    return (func(y+h) - func(y)) / h;
}
std::cout << D.Gradient(std::bind(&Root::Value, &R, std::placeholders::_1), 8) << std::endl;

也像Joachim Pileborg评论说您在Main中宣布功能,因此您需要删除()

编辑:

给出固定的参数,您可以执行以下操作:

int Optimize(const std::function<double(double)>& function_to_optimize, double &opt_val){
    opt_val = function_to_optimize(opt_val);
    return 0;
}
MySolver.Optimize(std::bind(&FunctionExample::Value, &F, std::placeholders::_1, 1), global_opt);

这将调用F.Value(opt_val, 1)。您也可以用固定的参数交换占位符。