Hello all
im trying to build function that will return void function pointer
what is mean is ( not working )
the main function
void * myClass::getFunction(int type){
if(type==1)
return &myClass::Test1;
if(type==2)
return &myClass::Test2;
}
This is how to use a function pointer, but it only works with global functions (not member functions in myClass). I have added some code, so that it's possible to compile and run this as a program. (Note that I had to add return 0 if no function was found, and I added a newline after the output from Test1 and Test2).
#include <cstdio>
using std::printf;
// Define the type func as a pointer to a void function with no parameters
typedefvoid (*func)();
void Test1() {
printf("nada1\n");
}
void Test2() {
printf("nada2\n");
}
func getFunction(int type) {
if(type==1)
return &Test1;
if(type==2)
return &Test2;
elsereturn 0;
}
int main() {
func p = 0;
p = getFunction(1);
(*p)();
p = getFunction(2);
(*p)();
}
#include <cstdio>
using std::printf;
class myClass {
public:
// Define the type func as a pointer to a void member function
// in this class with no parameters
typedefvoid (myClass::*func)();
func getFunction(int);
void Test1();
void Test2();
};
myClass::func myClass::getFunction(int type){
if(type==1)
return &myClass::Test1;
if(type==2)
return &myClass::Test2;
elsereturn 0;
}
void myClass::Test1(){
printf("nada1\n");
}
void myClass::Test2(){
printf("nada2\n");
}
int main() {
myClass c;
myClass::func p;
p = c.getFunction(1);
(c.*p)();
p = c.getFunction(2);
(c.*p)();
// Or using a pointer:
myClass *cp = &c;
p = cp->getFunction(1);
(cp->*p)();
p = cp->getFunction(2);
(cp->*p)();
}