Pointer to function in a C ++ class

4

I'm having trouble putting a pointer to a function in a class:

int Menu::validaescolha(){
    cout << 1232;
    return 1;
}
int Menu::inicial(){
    int (Menu::*funcs)() = &Menu::validaescolha;
    funcs();
    return 0;
}

Return these errors:

1 - Error (active) E0109 expressions preceding apparent call parenthesis must have function type (pointer-to-)

2 - Error C2064 term can not be evaluated as a function getting 0 arguments

I have no idea what to do here ...

    
asked by anonymous 26.02.2017 / 00:04

1 answer

4

Pointer to method is a not very used technique (I think), and so few people know. I had to search a bit to find out that you need to use additional parentheses when using the pointer. Note that it is necessary to have an object to call the method through the pointer.

This applies to non-static methods. Pointers to static methods are not special, they are declared in the same way as pointers to "common" functions (which are not members of a class).

#include <iostream>
using namespace std;

class Menu
{
   public:
      int validaEscolha();
      static int stValidaEscolha();
      int inicial();
};


int Menu::validaEscolha()
{
   cout << 1232 << endl;
   return 1;
}

int Menu::stValidaEscolha()
{
   cout << 1232 << endl;
   return 1;
}

int Menu::inicial()
{
   // ponteiro para método não estático
   int (Menu::*funcs)() = &Menu::validaEscolha;
   (this->*funcs)();

   // ponteiro para método estático
   int (*stFuncs)() = &Menu::stValidaEscolha;
   stFuncs();

   return 0;
}

int main()
{
   Menu m;
   m.inicial();
}
    
26.02.2017 / 16:20