Function pointer to member function
int (*x)()
is not a pointer to member function. A pointer to member function is written like this: int (A::*x)(void) = &A::f;
.
Call member function on string command
#include <iostream>
#include <string>
class A
{
public:
void call();
private:
void printH();
void command(std::string a, std::string b, void (A::*func)());
};
void A::printH()
{
std::cout<< "H\n";
}
void A::call()
{
command("a","a", &A::printH);
}
void A::command(std::string a, std::string b, void (A::*func)())
{
if(a == b)
{
(this->*func)();
}
}
int main()
{
A a;
a.call();
return 0;
}
Pay attention to (this->*func)();
and the way to declare the function pointer with class name void (A::*func)()
The syntax is wrong. A member pointer is a different type category from a ordinary pointer. The member pointer will have to be used together with an object of its class:
class A {
public:
int f();
int (A::*x)(); // <- declare by saying what class it is a pointer to
};
int A::f() {
return 1;
}
int main() {
A a;
a.x = &A::f; // use the :: syntax
printf("%d\n",(a.*(a.x))()); // use together with an object of its class
}
a.x
does not yet say on what object the function is to be called on. It just says that you want to use the pointer stored in the object a
. Prepending a
another time as the left operand to the .*
operator will tell the compiler on what object to call the function on.