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);
精彩评论