成员属性是C ++中的函数 [英] Member attributes that are functions in C++
问题描述
我正在尝试教自己一些C ++,作为一个初始项目,我想创建用于对单个变量的函数执行牛顿方法的代码.我要创建一个ObjectiveFunction
类,该类存储目标函数,一阶导数和二阶导数的用户定义函数.
I'm trying to teach myself some C++ and as an initial project, I want to create code for performing Newton's method on functions of a single variable. I want to make a class ObjectiveFunction
that stores user-defined functions for the objective function, the first derivative, and the second derivative.
我希望ObjectiveFunction
的构造函数采用0到3个参数,其中参数本身是函数:
I want the constructor of ObjectiveFunction
to take between 0 and 3 arguments, where the arguments themselves are functions:
// ObjectiveFunction.h
// Class definition for an Objective Function object.
#ifndef OBJECTIVE_H
#define OBJECTIVE_H
class ObjectiveFunction
{
public:
// Constructors
// Default constructor
ObjectiveFunction();
// Constructor with just objective function.
ObjectiveFunction(double f(double));
// Constructor with objective function and derivative function.
ObjectiveFunction(double f(double), double fp(double));
// Constructor with objective, derivative, and second derivative functions.
ObjectiveFunction(double f(double), double fp(double), double fpp(double));
// Methods
void setObjectiveFunction(double f(dobule));
void setDerivativeFunction(double f(double));
void setSecondDerivativeFunction(double f(double));
double evalObjectiveFunction(double);
double evalDerivativeFunction(double);
double evalSecondDerivativeFunction(double);
private:
// Storage for the functions.
// This is the part I'm not sure of.
// Attempt with function pointers
double (*objFunc)(double);
double (*d1Func)(double);
double (*d2Func)(double);
};
#endif // OBJECTIVE_H
我将如何创建本身就是函数的私有数据成员.我想创建可以访问的函数对象(私有对象除外),例如foo.obj_func(3.0)
或foo.deriv_func(3.0)
,其中obj_func
由构造函数根据用户传递给类的函数设置.
How would I create private data members that themselves are functions. I want to create functions objects that (except for being private) would be accessible like foo.obj_func(3.0)
or foo.deriv_func(3.0)
, where obj_func
gets set by the constructor based on the functions that the user passes to the class.
执行此操作的正确方法是什么?最好是有一种方法不依赖于使用指向函数对象的指针,但是我想如果那是唯一的方法,那便是我必须学习的方法.
What is the right way to do this? It would be best if there is a way that does not rely on using a pointer to a function object, but I guess if that's the only way then it's what I'll have to learn.
推荐答案
使用std::function<double(double)>
.这将使您能够轻松存储所有功能类型.
Use std::function<double(double)>
. This will enable you to store all function types easily.
这篇关于成员属性是C ++中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!