开发者

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

开发者 https://www.devze.com 2023-04-04 02:36 出处:网络
I have this code: #include <iostream> class foo { public: foo(int yy){y = yy;} void f(int x){std::cout<<开发者_运维技巧;x;}

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

精彩评论

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