I want to set the function pointer at runtime. But i’m stuck here. When i use global function or static class member function, everything is ok. but, when the function is ordinary class member functions. i always got compiler errors.
Here is the code:
class A
{
int val;
public:
A() { val = 0; }
A(int j) { val = j; }
int aFun(int k) {val -= k; return val; }
};
typedef int (* func)(int );
class B
{
func m_addr;
public:
B(func param)
: m_addr(param)
{
}
void execute()
{
cout << m_addr(9) << endl;
}
};
I’m trying to use them like this:
/* error C2355: ‘this’ : can only be referenced inside non-static
member functions error C2064: term does not evaluate to a function
taking 1 arguments class does not define an ‘operator()’ or a user
defined conversion operator to a pointer-to-function or
reference-to-function that takes appropriate number of arguments
*/
A a;
B b(A::aFun);
b.execute();
after googled a lot, i found that std::mem_fun may be helpful. but i don’t know how to use it. anyone can help me?
PS: i’m using Visual C++ 2010
Class member functions have an extra parameter passed to it the by the compiler called
this, so the compiler seesaFunas begin declared and written asStatic/global functions don’t have this parameter and so compilation succeeds.
In order to use
A::aFunyou’ll need an instance of classAsomewhere.