为什么回调函数在类中声明时需要是静态的 [英] Why callback functions needs to be static when declared in class

查看:603
本文介绍了为什么回调函数在类中声明时需要是静态的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was trying to declare a callback function in class and then somewhere i read the function needs to be static but It didn't explain why?

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


推荐答案

需要一个类实例被调用。
如果不提供要调用的实例,则无法调用成员函数。这使得有时很难使用。

A member function is a function that need a class instance to be called on. Members function cannot be called without providing the instance to call on to. That makes it harder to use sometimes.

静态函数几乎就像一个全局函数:它不需要一个类实例来调用。所以你只需要得到函数的指针就可以调用它。

A static function is almost like a global function : it don't need a class instance to be called on. So you only need to get the pointer to the function to be able to call it.

看看std :: function(或std :: tr1 :: function或boost :: function,如果你的编译器没有提供它),它在你的情况下是有用的,因为它允许你使用任何可调用(provide()语法或操作符)作为回调,包括可调用对象和成员函数std :: bind或boost :: bind)。

Take a look to std::function (or std::tr1::function or boost::function if your compiler doesn't provide it yet), it's useful in your case as it allow you to use anything that is callable (providing () syntax or operator ) as callback, including callable objects and member functions (see std::bind or boost::bind for this case).

这篇关于为什么回调函数在类中声明时需要是静态的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆