繁体   English   中英

作为班上“变量”成员

[英]Function as a member “variable” in class

我在考虑如何使用一些高级技术来改进我的简单计算器。 我来问一个问题,是否有某种方法可以用每个实例定义的函数来创建一个类:

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

#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";  
}

现场演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM