mchome
18th May 2012, 22:35
I want to use in my class a pointer to function.
I could not find a way.
This is a simple example that explains the difficulty:
class C{
public:
int First (int i, int j){return i;}
int Second(int i, int j){return j;}
int Fun(int);
};
int C::Fun(int i){
int (C::*pFun)(int, int);
if(i==1)
pFun=&C::First;
else
pFun=&C::Second;
return pFun(1,2); //ERROR
}
this causes an error message to be displayed.
I cannot find a way to solve this. On the other hand the non-member version works correctly, as follows:
int First(int i, int j);
int Second(int i, int j);
int First(int i, int j){ return i;}
int Second(int i, int j){ return j;}
int main (int argc, const char * argv[])
{
int i=1;
float x;
int (*fun)(int, int);
if(i==1)
fun=First;
else
fun=Second;
x=fun(1,2); //OK
}
Does anyone have any suggestion to give?
I could not find a way.
This is a simple example that explains the difficulty:
class C{
public:
int First (int i, int j){return i;}
int Second(int i, int j){return j;}
int Fun(int);
};
int C::Fun(int i){
int (C::*pFun)(int, int);
if(i==1)
pFun=&C::First;
else
pFun=&C::Second;
return pFun(1,2); //ERROR
}
this causes an error message to be displayed.
I cannot find a way to solve this. On the other hand the non-member version works correctly, as follows:
int First(int i, int j);
int Second(int i, int j);
int First(int i, int j){ return i;}
int Second(int i, int j){ return j;}
int main (int argc, const char * argv[])
{
int i=1;
float x;
int (*fun)(int, int);
if(i==1)
fun=First;
else
fun=Second;
x=fun(1,2); //OK
}
Does anyone have any suggestion to give?