首页 > 解决方案 > 将函数指针传递给类对象

问题描述

我需要能够为一个能够运行的类指定一个函数(回调函数?)作为菜单系统的一部分,我对 c++ 的了解在这里延伸。显然这不会编译,但希望它能让我了解我正在尝试做的事情 -

void testFunc(byte option) {
  Serial.print("Hello the option is: ");
  Serial.println(option);
}

typedef void (*GeneralFunction)(byte para);
GeneralFunction p_testFunc = testFunc;

class testClass {
    GeneralFunction *functionName;
  public:
    void doFunction() {
      functionName;
    }
};

testClass test { *p_testFunc(123) };

void setup() {
  Serial.begin(9600);
  test.doFunction();
}

void loop() {
 
}

我知道一些 std:: 选项,但不幸的是,Arduino 没有实现它们。

编辑:此代码的编译器输出 -

sketch_mar10a:17:29: error: void value not ignored as it ought to be

 testClass test { *p_testFunc(123) };

                             ^

sketch_mar10a:17:35: error: no matching function for call to 'testClass::testClass(<brace-enclosed initializer list>)'

 testClass test { *p_testFunc(123) };

                                   ^

标签: c++classpointersarduino-c++

解决方案


请找到下面的代码,看看这是否有帮助,你需要一个构造函数来获取参数,你也不能从参数列表中调用函数,而它需要一个函数指针

#include <iostream>

using namespace std;

void testFunc(int option) {
  std::cout<<"in fn "<<option;
}

typedef void (*GeneralFunction)(int para);
GeneralFunction p_testFunc = testFunc;

class testClass {
    GeneralFunction functionName;
    int param1;
  public:
    testClass(GeneralFunction fn,int par1):functionName(fn),param1(par1){}
    void doFunction() {
      functionName(param1);
    }
};

testClass test (p_testFunc,123);

void setup() {
  test.doFunction();
}

void loop() {

}


int main()
{
    setup();
    return 0;
}

推荐阅读