在引用类构造函数时定义私有函数

时间:2018-05-10 03:43:41

标签: c++ function class constructor

我想创建一个类Function,它可以使用float方法并使用它从函数中生成有用的值。但是,我不明白如何在构造函数中声明一个私有方法作为参数传递的方法。

希望这堂课有助于理解我的意图:

#include <iostream>
#include <math.h>


class Function {
    float function(float x);
    public:
        Function(float method(float)) {
            // how do I set private function "function" equal to passed function "method"?
        };
        float eval(float x) {
            return function(x);
        }
        float derive(float x, float error = 0.001) {
            return (function(x) - function(x + error)) / error;
        }
        float integrate(float x0, float x1, float partitions = 100) {
            float integral = 0;
            float step = (x1 - x0) / partitions;
            for(float i = 0; i < partitions; i += step) integral += step * function(i);
            return integral;
        }
};


float exampleFunction(float x) {
    return 2 * pow(x, 2) + 5;
}


int main() {
    Function myFunction (exampleFunction);

    std::cout << myFunction.eval(6);
}

解决可能的重复:

标记的问题是询问是否使用指向已构造的类实例中的方法的指针来调用构造函数。我试图将指针传递给构造函数来定义新类的私有方法。

2 个答案:

答案 0 :(得分:2)

使用

  // The member variable that stores a pointer to a function.
  float (*function)(float);

  // The constructor.
  // Store the passed function in the member variable.
  Function(float method(float)) : function(method) {}

Working demo

答案 1 :(得分:0)

使用typedef更容易:

using func_t = float(float);

class Function {
    func_t* function = nullptr;
public:
    Function(func_t* f) : function(f) {}
    // ...
};
相关问题