简体   繁体   English

如何将一个成员函数传递给另一个成员函数?

[英]How to pass a member function to another member function?

My problem is about passing a member function from a Class A, to a member function of a Class B: 我的问题是关于将成员函数从A类传递到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, moteurGraphique是一个类, moteurGraphique::drawSprite是一个成员函数,

defaultScene is an instance of B class, and boucle is B member function. defaultScene是B类的实例,而boucle是B成员函数。

All that is called in a member function of A: 在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 ? 我认为我做错了什么,有人可以解释我的错误吗?

C++11 way: C ++ 11方式:

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));

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
}

Can't you make drawMyThing a static function if you don't need to instantiate A, and then do something like : 如果不需要实例化A,然后执行类似以下操作,就不能将drawMyThing设为静态函数:

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

?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM