问题
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