Reputation: 958
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
Upvotes: 0
Views: 231
Reputation: 512
I didn't get exactly what are you trying to do but I saw an error, maybe helps you.
That's a pointer to a function, isn't?
typedef int (* func)(int );
But you don't have a function, you have a method of a class. (a member function) So the typedef shoud be probability:
typedef int (A::*func)(int );
I hope helps you a bit, you can google for pointers to member functions and you will find some examples.
Good luck!
Upvotes: 0
Reputation: 141
modified as following:
static int val;
class A
{
public:
A() { val = 0; }
A(int j) { val = j; }
static int aFun(int k) {val -= k; return val; }
};
Upvotes: 0
Reputation: 9288
Class member functions have an extra parameter passed to it the by the compiler called this
, so the compiler sees aFun
as begin declared and written as
int A::aFun(A* this, int k)
{
this->val -= k;
return this->val;
}
Static/global functions don't have this parameter and so compilation succeeds.
In order to use A::aFun
you'll need an instance of class A
somewhere.
Upvotes: 4