簡體   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