I am trying to better understand the concept of pointer function. Therefore, I have a very simple and working example:
#include <iostream> using namespace std; int add(int first, int second) { return first + second; } int subtract(int first, int second) { return first - second; } int operation(int first, int second, int (*functocall)(int, int)) { return (*functocall)(first, second); } int main() { int a, b; int (*plus)(int, int); int (*minus)(int, int); plus = &add; minus = &subtract; a = operation(7, 5, add); b = operation(20, a, minus); cout << "a = " << a << " and b = " << b << endl; return 0; }
So far so good. Now I need to group the functions in the class and select add or subtract based on the function pointer that I use. So I'm just doing a little modification like:
and obvious error:
ptrFunc.cpp: In function 'int main()': ptrFunc.cpp:87:29: error: invalid use of non-static member function 'int A::add(int, int)' ptrFunc.cpp:88:30: error: invalid use of non-static member function 'int A::subtract(int, int)'
coz I did not specify which object to call (and so far I do not want to use static methods)
EDIT: a few comments and answers suggested that a non-static version (as I wrote) is not possible (thanks to everyone) So modifying the class as follows also doesn't work:
generated this error:
ptrFunc.cpp: In constructor 'A::A(int)': ptrFunc.cpp:11:30: error: cannot convert 'A::add' from type 'int (A::)(int, int)' to type 'int (*)(int, int)' ptrFunc.cpp:12:31: error: cannot convert 'A::subtract' from type 'int (A::)(int, int)' to type 'int (*)(int, int)'
Can I find out how to solve this problem?
thanks