c++ - 如何从函数数组中调用特定函数?

标签 c++ arduino arduino-c++

我正在开发基于 Arduino/ATMega 的 watch 。现在的主要目标是通过按下侧面的按钮在“模式”(不同的功能)之间切换。最初,我有一个很长的 if 语句,如下所示:

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

但这似乎效率低下。因此,我尝试在不实际调用它们的情况下创建一个函数数组,然后稍后调用索引函数。代码段如下(抱歉乱七八糟,这是一个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]();
}
但是,当我尝试编译它时,出现错误:

Error: expression cannot be used as a function.


该逻辑在 Python 中有效,所以我假设有一个我不知道的概念在高级语言中被抽象掉了。我很愿意学习它,我只需要知道它是什么。

最佳答案

类型错误 - 而不是 int你需要void (*)()作为类型(因为你有一个 void someFunction() 函数指针数组,而不是整数数组 - 虽然前者可以以某种方式转换为后者,但作为内存地址,你不能调用整数)。

void (*Modes[3])() = {showTime, flashlight, antiAnxiety};
通过类型定义,这段代码变得更容易理解:
typedef void (*func_type)();
func_type Modes[3] = {showTime, flashlight, antiAnxiety};

关于c++ - 如何从函数数组中调用特定函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63455486/

相关文章:

c++ - 使用可变参数模板创建模板类元组

arduino - 当我按下 Enter 键时 PuTTY 会发送什么?

arduino - 使 ESP32 WiFi/蓝牙协同工作

c++ - 使用可变参数模板重载函数模板 : Intel c++ compiler version 18 produces different result from other compilers. intel 错了吗?

C++ 时间戳和 diffTime

c++ - c++ 中的 hbrBackground

c - Arduino Error all of overloaded ‘println(long unsigned int (&)())’ is ambiguous 错误

c - 使用 Arduino mega 2560 与 Arduino2max 数字引脚进行通信

c++ - AVR CTC 模式下的 16 位定时器

c++ - 在 Arduino UNO 编程中,当您希望同时执行不同的功能时,使用什么代码/语句?