将函数指针传递给类对象

时间:2021-03-10 10:20:22

标签: c++ class pointers arduino-c++

我需要能够为一个类指定一个函数才能作为菜单系统的一部分运行(回调函数?),我的 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) };

                                   ^

2 个答案:

答案 0 :(得分:2)

请找到下面的代码,看看这是否有帮助,您需要一个构造函数来获取参数,并且您不能在需要函数指针的同时从参数列表中调用该函数

#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;
}

答案 1 :(得分:0)

感谢 Bibin,我修改了他的代码以适应 Arduino,分离构造函数,并在 setup() 中初始化类。

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;
    byte param1;
  public:
    testClass(GeneralFunction fn, int par1);
    void doFunction() {
      functionName(param1);
    }
};

void setup() {
  Serial.begin(9600);
  testClass test (p_testFunc, 123);
  test.doFunction();
}

void loop() {
}

testClass::testClass(GeneralFunction fn, int par1)  //constructor
  : functionName(fn), param1(par1) {}

输出:

Hello the option is: 123