一个类应使用功能指针调用另一类的方法
one class should invoke method of another class using a function pointer
我有咨询(免责声明):
- 类成员功能指针
- 通过功能指针调用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)
。您也可以用固定的参数交换占位符。
相关文章:
- 在c++中多次调用方法
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 接收字符串并使用它来调用方法C++
- 使用 gmock c++ 在真实对象上调用方法
- 不带预处理器的调用方法/文件的文件名/行号
- JNI从Android调用C++方法
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何使用接口指针调用方法,该指针是其具体类的一部分,而不是接口的一部分
- 从内部类中的方法从包含类调用方法
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 为什么派生类的实例从基类调用方法?
- 实例化对象并调用方法,使用单行语法在 C# 或 C++ 中返回值?
- C++当您取消引用指向类对象的指针,然后将其作为引用返回时,是否可以对此引用调用方法
- 通过模板函数对未知类型调用方法
- 从基于迭代器的for循环转换后,如何在map::find()中调用方法
- 创建一个C++DLL以从C#DLL调用方法
- 如何从qt中的类中调用方法
- 如何在不迭代的情况下对数组中的每个元素调用方法
- C++11 - 获取编译时的所有类变量,并在没有 Boost 的情况下为它们调用方法
- C ++:如何在不创建对象的情况下在主函数中调用方法