开发者

How to call member function using function pointers for a specific object

I have this code:

#include <iostream>

class foo
{
    public:
        foo(int yy){y = yy;}
        void f(int x){std::cout<<开发者_运维技巧;x;}

    private:
        int y;
};

void main()
{
    foo* obj = new foo(123);
    void (foo::*func)(int) = &foo::f;

    //how do I call func with obj as this?
    delete obj;
}

Is this possible?


You call it ike this:

(obj->*func)(42);

The first set of parentheses are needed because of the precedence of "apply function call" over the dereference-PTM ->* operator.

You can also use std::bind:

std::function<void(int)> my_f = std::bind(func, obj, std::placeholders::_1);

my_f(43);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜