从类 A 到类 B 的方法的 void 指针

Void pointer from class A to method from class B

本文关键字:方法 指针 void 到类 从类      更新时间:2023-10-16

我需要知道是否可以"转换"从一个类到另一个类的成员变量的方法所以我可以从另一个类(例如从 bar)调用此方法(例如来自 foo)

应该看起来像

void bar::setFunction( void(*f)())
{
    /*bar::*/func = f; // func <= void (*func)();
}
int main()
{
    foo myclass;
    bar myotherclass;
    bar.setFunction( &myotherclass.dosth);
}

这解决了我的问题:

typedef std::function<void()> Func;
class bar
{
public:
    void setFunction( std::function<void()> f ) {
        func = f;
    }
    void call()
    {
        func();
    }
private:
    Func func;
};
class foo
{
public :
    static void dosth()
    {
        std::cout << "hallo" << std::endl;
    }
};

int main( int argc, char** argv )
{
    foo myclass;
    bar myotherclass;
    Func fd = &myclass.dosth;
    myotherclass.setFunction( fd );
    myotherclass.call(); // this calls the foo method dosth -> "hallo"
    _sleep( 600 );
}