簡體   English   中英

如何從函數數組中調用特定的 function?

[英]How to call a specific function from an array of functions?

我正在開發基於 Arduino/ATMega 的手表。 現在的主要目標是通過按下側面的按鈕在“模式”(不同的功能)之間切換。最初,我有一個很長的 if 語句,如下所示:

if (counter == 0) 
    mode1();
    enter code 
else if (counter == 1)
    mode2();
    .... Repeat....

但這似乎效率低下。 因此,我嘗試在不實際調用它們的情況下創建一個函數數組,然后稍后調用索引的 function。 代碼段如下(抱歉混亂,這是一個WIP)


int Modes[3] = {showTime,flashlight,antiAnxiety} //these are all void functions that are defined earlier. 

int scroller(){
  int counter = 0;
    int timeLeft = millis()+5000;
    while (timer <= millis()){
       ...more code...
    }
  Modes[counter]();
}

但是,當我嘗試編譯它時,出現錯誤:

錯誤:表達式不能用作 function。

該邏輯在 Python 中有效,所以我假設有一個我不知道的概念在高級語言中被抽象掉了。 我很願意學習它,我只需要知道是什么。

類型錯誤 - 而不是int你需要void (*)()作為類型(因為你有一個void someFunction() function 指針數組,而不是整數數組 - 而前者可以轉換為后者方式,作為 memory 地址,不能調用整數)。

void (*Modes[3])() = {showTime, flashlight, antiAnxiety};

通過類型定義,這段代碼變得更容易理解:

typedef void (*func_type)();
func_type Modes[3] = {showTime, flashlight, antiAnxiety};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM