【问题标题】:Define private function in reference to class constructor参考类构造函数定义私有函数
【发布时间】:2018-10-20 06:23:37
【问题描述】:

我想创建一个类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);
}

解决可能的重复问题:

带标签的问题是询问如何使用指向已构造类实例中的方法的指针来调用构造函数。我正在尝试将指针传递给构造函数来定义新类的私有方法。

【问题讨论】:

标签: c++ function class constructor


【解决方案1】:

使用

  // 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.

【讨论】:

  • FWIW,你可以考虑std::function&lt;float(float)&gt;
【解决方案2】:

使用 typedef 更容易:

using func_t = float(float);

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

【讨论】:

    猜你喜欢
    • 2011-02-08
    • 1970-01-01
    • 2017-08-20
    • 2023-01-01
    • 1970-01-01
    • 2011-04-20
    • 2015-01-22
    • 2019-10-16
    相关资源
    最近更新 更多