在 C++ 中作为函数的成员属性 [英] Member attributes that are functions in C++

查看:21
本文介绍了在 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.这将使您能够轻松存储所有函数类型.

Use std::function<double(double)>. This will enable you to store all function types easily.

这篇关于在 C++ 中作为函数的成员属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆