【问题标题】:Function as a member "variable" in class作为类中的成员“变量”起作用
【发布时间】: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&lt;int(int, int)&gt;,然后您可以使用 lambda 构造 Function:例如:Function divide([](int x,int y){return x / y;}); 但是我不确定您的Function 提供了您不能只使用 std::function 的产品。

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

【问题讨论】:

  • 你的意思是一个函数指针之类的东西:int (*function)(int,int))?
  • 你的意图是什么?你能提供更多的例子吗?
  • @πάνταῥεῖ 是这样的
  • std::function&lt;int(int, int)&gt; 也可能有助于二进制功能。

标签: c++ calculator


【解决方案1】:

当然,您的Function 可以存储std::function&lt;int(int, int)&gt;,然后您可以使用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";  
}

Live demo.

但是,就目前而言,我不确定 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";  
}

Live demo.

【讨论】:

  • 使用函数作为成员具有多态行为的优势,通过切换相同接口但具有不同实现的函数(可以在构造时或在运行时)。例如来自形状对象的 draw()。形状可以是三角形或圆形。这发生在我的某些项目的设计中(你不想启动新的派生类,只想使用不同的方法)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-25
  • 1970-01-01
  • 2013-10-26
  • 1970-01-01
  • 1970-01-01
  • 2021-08-05
相关资源
最近更新 更多