这是一些代码:

typedef void (*ACallBack)(int i);

class SomeClass
{
private:
   ACallBack aCallBack;

public:
   void SetCallBack(ACallBack aCallBack);
};

void SomeClass::SetCallBack(ACallBack aCallBack)
{
   this->aCallBack = aCallBack;
}

class SomeOtherClass
{
private:
   SomeClass someClass;

public:
   void InitializeSomeClass();

private:
   void callBackMethod(int i);
};

void SomeOtherClass::InitializeSomeClass()
{
   this->changeVariable = 10;

   this->someClass.SetCallBack(this->callBackMethod); // DOESN'T WORK
   this->someClass.UseCallBack();
}

void SomeOtherClass::callBackMethod(int i)
{
}

void globalCallBack(int i)
{
   int myInt = i;
}

int main()
{
   SomeClass sC;
   sC.SetCallBack(globalCallBack); //WORKS!!
}


基本上,如果我尝试在SomeOtherClass中设置回调函数不起作用,但是当我在main中全局设置它时,它将起作用。我在这里想念什么?

最佳答案

只需使用std::functionstd::bind()

typedef std::function<void(int i)> ACallBack;

// old code pretty much the same

int main()
{
    using namespace std::placeholders;

    SomeClass sC;
    sC.SetCallBack(globalCallBack); //WORKS!!
    SomeOtherClass oC;
    sC.SetCallBack(std::bind(&SomeOtherClass::callBackMethod,oC,_1)); //WORKS AS WELL!!
}


在这种情况下,您实际上不需要传递void *userData,但如果需要旧代码进行编译,也可以添加它。

07-24 09:55