简体   繁体   English

c ++中的回调函数

[英]callback function in c++

The code describes two classes that implement callback function, the function must should be member function in the class parameter that passed in template. 代码描述了两个实现回调函数的类,该函数必须是在模板中传递的类参数中的成员函数。 Below the code i attached the relevent error message i get. 在代码下面,我附上了相关的错误消息。

ah

template <class CLASSNAME>
class a
{
public:
    typedef void (CLASSNAME::*myFunction)();

    a(CLASSNAME& myObject, myFunction callback) :
    m_myObject(myObject)
    {
        m_myFuntion = callback;
    }

    void update()
    {
        (m_myObject).*(m_myFuntion);
    }

    myFunction m_myFuntion;
    CLASSNAME& m_myObject;
};

dummy.h dummy.h

#include <stdio.h>

class dummy
{
public:
    dummy()
    {
        var = 14;
    }


    void func()
    {
        printf("func!!");
    }

    int var;
};

main.cpp main.cpp中

#include <cstdlib>
#include "a.h"
#include "dummy.h"


void main()
{
    dummy dum;

    a<dummy> avar(dum, &(dummy::func));

    avar.update();

    system("pause");
}

i am trying to implement the callback function and i get the following error message: 我正在尝试实现回调函数,我收到以下错误消息:

C2298 missing call to bound pointer to member function  

what the problem is? 问题是什么?

You have a lot of parentheses, they're just not in the right place. 你有很多括号,他们只是不在正确的地方。 The correct syntax for calling a pointer-to-member function is: 调用指向成员函数的函数的正确语法是:

void update()
{
    (m_myObject.*m_myFuntion)();
}

You are using parentheses in the wrong places: 您在错误的地方使用括号:

This: 这个:

 a<dummy> avar(dum, &(dummy::func));

should be this: 应该这样:

 a<dummy> avar(dum, &dummy::func);

And this: 和这个:

(m_myObject).*(m_myFuntion);

should be: 应该:

(m_myObject.*m_myFuntion)();

Live Example 实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM