【发布时间】:2015-06-21 12:32:15
【问题描述】:
我正在考虑如何使用一些高级技术来改进我的简单计算器。我开始质疑,是否有某种方法可以创建一个具有您可以为每个实例定义的函数的类:
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 的产品。
它回答了我的问题,不幸的是我的问题被搁置了,所以我无法将问题标记为已解决。
【问题讨论】:
-
你的意思是一个函数指针之类的东西:
int (*function)(int,int))? -
你的意图是什么?你能提供更多的例子吗?
-
@πάνταῥεῖ 是这样的
-
std::function<int(int, int)>也可能有助于二进制功能。
标签: c++ calculator