在类中充当成员"variable"



我在考虑如何使用一些高级技术改进我的简单计算器。我提出了一个问题,有没有办法创建一个具有每个实例可以定义的函数的类:

class Function
{
public:
    Function(function);
    ~Function();
private:
    function;
};

例如,您创建了一个实例

Function divide(int x / int y); //For example

我希望你能理解这个问题。

编辑:

因此,我研究了void (*foo)(int)方法。它是可以使用的。但最初的想法是创建一个通用函数,将函数本身保存在其中。而不仅仅是指向外部定义的函数的指针。所以你可以这样做:

int main() {
//Define the functions
Function divide( X / Y ); //Divide
Function sum( X + Y ); //Sum
//Ask the user what function to call and ask him to enter variables x and y
//User chooses divide and enters x, y 
cout << divide.calculate(x, y) << endl;
return 0;
}

答案:@Chris Drew指出:
当然,你的Function可以存储std::function<int(int, int)>,然后你可以用lambda构造Function:例如:Function divide([](int x,int y){return x / y;});。但我不确定你的Function提供了什么,你不能只使用std::function

它回答了我的问题,不幸的是,我的问题被搁置了,所以我无法标记问题已解决。

当然,您的Function可以存储std::function<int(int, int)>,然后您可以使用lambda:构建Function

#include <functional>
#include <iostream>
class Function {
  std::function<int(int, int)> function;
public:
  Function(std::function<int(int, int)> f) : function(std::move(f)){};
  int calculate(int x, int y){ return function(x, y); }
};
int main() {
  Function divide([](int x, int y){ return x / y; });
  std::cout << divide.calculate(4, 2) << "n";  
}

现场演示。

但是,就目前情况来看,我不确定Function提供了什么,而你不能直接使用std::function

#include <functional>
#include <iostream>
using Function = std::function<int(int, int)>;
int main() {
  Function divide([](int x, int y){ return x / y; });
  std::cout << divide(4, 2) << "n";  
}

现场演示。

最新更新