[英]How do I declare an array of functions?
這是CMD提示計算的一部分:
1)使用0-9顯示選項
2)用戶輸入與其所需功能匹配的數字
而不是10: case i: //do stuff here
我可以有一個包含函數的數組嗎?
functionArrayName = [(float cosx(float _cx);), (float sinx(float _sx);) ... etc ]
然后有一個for循環:
for(int i = 0; i < 10; ++i){
if(i = userInput){
//call the function in functionArrayName[i];
}}
丑陋,但是,嘿,這就是你要的...
float (*arr[])(float) = { cosf, sinf,...};
...
float result = arr[i]();
您似乎來自更“靈活”的語言,順便說一句。
無論如何,您的代碼有幾個錯誤:
首先,最重要的是:
functionArrayName = [(float cosx(float _cx);), (float sinx(float _sx);) ... etc ]
實際上應該是:
#include <array>
#include <functional>
// ...
std::array<std::function<float(float)>> functionArrayName;
請注意,此std::array
只能容納返回float
並采用單個float
參數的函數(類似)對象。
其次...
if(user = input) {
在大多數情況下應為:
if(user == input) {
盡管(僅在某些情況下)該表達式有效,但它通常表示對比較運算符有誤解。
希望這可以幫助!
以下內容與您要求的內容基本相似,但使用的是現代C ++
#include <functional>
extern float cosx(float);
extern float sinx(float);
// ... add more
std::function<float(float)> functionArray[] = {cosx, sinx, /*... add more */};
int main() {
int userInput = 0;
float x = 3.14159/2;
float y = functionArray[userInput](x);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.