为什么回调函数在类中声明时需要是静态的

cpx*_*cpx 16 c++ callback

我试图在类中声明一个回调函数,然后在某处我读取函数需要是静态的,但它没有解释为什么?

#include <iostream>
using std::cout;
using std::endl;

class Test
{
public:
    Test() {}

    void my_func(void (*f)())
    {
        cout << "In My Function" << endl;
        f(); //Invoke callback function
    }

    static void callback_func()
    {cout << "In Callback function" << endl;}
};

int main()
{
    Test Obj;
    Obj.my_func(Obj.callback_func);
}
Run Code Online (Sandbox Code Playgroud)

Kla*_*aim 20

成员函数是需要调用类实例的函数.如果不提供要调用的实例,则无法调用成员函数.这使得有时使用起来更加困难.

静态函数几乎就像一个全局函数:它不需要调用类实例.因此,您只需要获取指向函数的指针即可调用它.

看一下std :: function(或std :: tr1 :: function或boost :: function,如果你的编译器还没有提供它),它在你的情况下是有用的,因为它允许你使用任何可调用的东西(提供()语法或运算符)作为回调,包括可调用对象和成员函数(对于这种情况,请参阅std :: bind或boost :: bind).


Pau*_*l R 8

回调需要是静态的,以便它们没有隐式this参数作为其函数签名中的第一个参数.