How do I get the function pointer assignments (and maybe the rest) in test.calculate to work?
#include <iostream>
class test {
int a;
int b;
int add (){
return a + b;
}
int multiply (){
return a*b;
}
public:
int calculate (char operatr, int operand1, int operand2){
int (*opPtr)() = NULL;
a = operand1;
b = operand2;
if (operatr == '+')
opPtr = this.*add;
if (operatr == '*')
opPtr = this.*multiply;
return opPtr();
}
};
int main(){
test t;
std::cout << t.calculate ('+', 2, 3);
}
There are several problems with your code.
First,
int (*opPtr)() = NULL;
isn't a pointer to a member function, its a pointer to a free function. Declare a member function pointer like this:int (test::*opPtr)() = NULL;
Second, you need to specify class scope when taking the address of a member function, like this:
Finally, to call through a member function pointer, there is special syntax:
Here is a complete working example: