How to pass a member function to another member function?

空扰寡人 提交于 2021-01-28 21:44:41

问题


My problem is about passing a member function from a Class A, to a member function of a Class B:

I tried something like this :

typedef void (moteurGraphique::* f)(Sprite);
f draw =&moteurGraphique::drawSprite;
defaultScene.boucle(draw);

moteurGraphique is A class, moteurGraphique::drawSprite is A member function,

defaultScene is an instance of B class, and boucle is B member function.

All that is called in a member function of A:

void moteurGraphique::drawMyThings()

I tried different ways to do it, that one seems the more logical to me, but it won't work! I got:

Run-Time Check Failure #3 - The variable 'f' is being used without being initialized.

I think I am doing something wrong, can someone explain my mistake ?


回答1:


C++11 way:

using Function = std::function<void (Sprite)>;

void B::boucle(Function func);
...

A a;
B b;

b.boucle(std::bind(&A::drawSprite, &a, std::placeholders::_1));



回答2:


Member functions need to be called on objects, so passing the function pointer alone is not enough, you also need the object to call that pointer on. You can either store that object in the class that is going to call the function, create it right before calling the function, or pass it along with the function pointer.

class Foo
{
public:
    void foo()
    {
        std::cout << "foo" << std::endl;
    } 
};

class Bar
{
public:
    void bar(Foo * obj, void(Foo::*func)(void))
    {
        (obj->*func)();
    }
};

int main()
{
    Foo f;
    Bar b;
    b.bar(&f, &Foo::foo);//output: foo
}



回答3:


Can't you make drawMyThing a static function if you don't need to instantiate A, and then do something like :

defaultScene.boucle(A.drawMyThing(mySpriteThing));

?



来源:https://stackoverflow.com/questions/33098050/how-to-pass-a-member-function-to-another-member-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!