2014-02-08 52 views
0
#include<iostream> 

class Bar; 

class Foo{ 
public: 
    void (Bar::*callback)(void); 
    Bar* bar; 
    Foo(Bar* bar, void (Bar::*cb)(void)){ 
     callback = cb; 
    } 
    void execute(){ 
     (bar->*callback); // commenting out this will make it compile 
     // i want to execute callback here, but can't find a way to do it 
    } 
}; 

class Bar{ 
public: 
    Foo *f; 

    Bar(){ 
     f = new Foo(this, &Bar::func); 
     f->execute(); 
    } 

    void func(){ // this can't be static 
     std::cout << "func executed" << std::endl; 
    } 
}; 

int main(){ 
    Bar b; 

    return 0; 
} 

这就是我想要做的,我需要做一个回调例如一个按钮。 但我不能调用成员函数指针。成员函数的C++回调

还是另一种方式,我应该用它来获得此功能?

编辑:我得到的错误是“非法使用非静态成员函数” 使函数静态不是一个选项。

+0

您需要的std ::功能 –

+0

你得到一个错误?它是什么? – 0x499602D2

回答

0
(bar->*callback); 

你不在这里调用该函数,只是取消引用它:

(bar->*callback)(); 
//    ^^ 
+0

嗯,我很确定我已经尝试过,但确实有效。 – lasvig