简体   繁体   中英

Why can't I access the pointer to my member function in my array?

I have class with an array of pointers to class methods. However, in the class, when I try to call one of the function in the array, I get an error. Here is the relevant code:

class MyClass
{
typedef void(MyClass::*FunctionPointer)(size_t *i);
void func1(size_t *i) { }
void func2(size_t *i) { }
void func3(size_t *i) { }
void func4(size_t *i) { }

FunctionPointer myFuncs[4] = { func1, func2, func3, func4 };
const std::string funcList[4] = { "FUNC1", "FUNC2", "FUNC3", "FUNC4" };

void doFunc(std::string in)
{
   size_t *j = 0;
   for (size_t i = 0; i < 4; ++i)
   {
      if (in == funcList[i]) { this->myFuncs[i](j); }           
   }
}
};

I have tried omitting "this->" as well as "this->*" and nothing is working. The error I am getting is "expression preceding parentheses of apparent call must have (pointer-to-) function type." Which according to the internet means that I am trying to call something that is not defined as a function. But I am pretty sure that I am? Thanks

You can if you follow the correct syntax ;) Get the address of the method using:

&MyClass::func1

Then to resolve the function pointer, do:

(this->*myFuncs[i])

or in full...

class MyClass
{
typedef void(MyClass::*FunctionPointer)(size_t *i);
void func1(size_t *i) { }
void func2(size_t *i) { }
void func3(size_t *i) { }
void func4(size_t *i) { }

FunctionPointer myFuncs[4] = { &MyClass::func1, &MyClass::func2, &MyClass::func3, &MyClass::func4 };
const std::string funcList[4] = { "FUNC1", "FUNC2", "FUNC3", "FUNC4" };

void doFunc(std::string in)
{
   size_t *j = 0;
   for (size_t i = 0; i < 4; ++i)
   {
      if (in == funcList[i]) { (this->*myFuncs[i])(j); }           
   }
}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM