【问题标题】:Pass a function pointer to a class object将函数指针传递给类对象
【发布时间】:2021-03-10 10:20:22
【问题描述】:

我需要能够为一个类指定一个函数(回调函数?)作为菜单系统的一部分,我的 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++ class pointers arduino-c++


【解决方案1】:

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

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

【讨论】:

  • 谢谢,这适用于 Arduino。阅读 Arduino 类初始化我认为建议在 setup() 中进行,所以我已经分离出构造函数(为了稍后的可读性),并将初始化移至 setup,并将其作为答案发布。
  • 如果这有助于您将函数指针传递给类对象,请将其标记为答案
【解决方案2】:

感谢 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-06
    • 2014-03-31
    • 2023-03-27
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多