【问题标题】:C++ Arduino: assign a Function to function pointer [duplicate]C ++ Arduino:将函数分配给函数指针[重复]
【发布时间】:2016-10-23 06:24:50
【问题描述】:

我有一个包含两个类似的非静态函数的类,我想将其中一个动态分配给函数指针:

啊哈:

class A{
    private:
    void (*funcPtr)(int);
    void do_sth(int i);
    void do_sth_else(int i);
}

A.cpp:

A::A(int i){
    if(i == 1)
        A::funcPtr = A::do_sth; // or &A::do_sth;
    else 
        A::funcPtr = A::do_sth_else; // or &A::do_sth_else;
}

但我得到这样的错误:

error: cannot convert 'A::do_sth' from type 'void (A::)(int)' to type 'void (*)(int)'

我阅读了多个类似的问题,但无法将他们的解决方案应用于我的问题。

【问题讨论】:

  • 考虑到 Arduino 的内存限制,函数指针可能有点过于复杂。如果编译器可以处理它,为什么不使用lambdas

标签: c++


【解决方案1】:

这些是成员函数。通过使用类名限定 funcPtr 将其设为成员指针,或者将 do_sth()do_sth_else() 设为静态成员函数。我建议在获取地址时在函数名前使用&

【讨论】:

    猜你喜欢
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 2015-10-15
    • 1970-01-01
    相关资源
    最近更新 更多