简体   繁体   中英

array of pointers to member functions

I am having a problem with this code because compiler doesn't allows me to run code because says that

cannot convert 'void (Menu::*)(int)' to 'void (Menu::*)(int*)' in assignment. 

And I know that this program can be executed with normal functions. I've read something of typedef but I have not been programming for a while and my English is not native. Code has some words in spanish but doesn't affects the code, I can translate if you want but I think it's easy to understand. I will appreciate it if somebody can help me.

#include "Menu.h"

#include<iostream>
using std::cout;
using std::endl;
using std::cin;

int main()
{
    void (Menu::*fptr[3])( int*);

    typedef void (Menu::*funcion0)( int &)

    fptr[0] = &Menu::funcion0;  //problem
    fptr[1] = &Menu::funcion1;  //problem
    fptr[2] = &Menu::funcion2;  //problem

    //void (*f[ 3 ])( int ) = { &Menu::funcion0, &Menu::funcion1, &Menu::funcion2 };

    int opcion;

    cout << "Escriba un numero entre 0 y 2, 3 para terminar: ";
    cin >> opcion;

    while ( ( opcion >= 0 ) && ( opcion < 3 ) )
    {
        //(*f[ opcion ])( opcion );

        cout << "Escriba un numero entre 0 y 2, 3 para terminar: ";
        cin >> opcion;
    }

    cout << "Se completo la ejecucion del programa." << endl;

    return 0;

}

Menu.h header file

#ifndef MENU_H_INCLUDED
#define MENU_H_INCLUDED

class Menu
{
    public:
        Menu();
        void funcion0( int );
        void funcion1( int );
        void funcion2( int );
};

#endif // MENU_H_INCLUDED

Menu.cpp

#include "Menu.h"

#include <iostream>
using std::cout;
using std::cin;

Menu::Menu()
{

}

void Menu::funcion0( int a )
{
    cout << "Usted escribio " << a << " por lo que se llamo a la funcion0\n\n";
}

void Menu::funcion1( int b )
{
    cout << "Usted escribio " << b << " por lo que se llamo a la funcion1\n\n";
}

void Menu::funcion2( int c )
{
    cout << "Usted escribio " << c << " por lo que se llamo a la funcion2\n\n";
}

Your member functions take int as argument, but you make array of pointers to member functions as if arguments were pointer of type int* . Pointer to function arguments and return type must be exactly same as function's that is pointed to. Change:

void (Menu::*fptr[3])( int*);

to:

void (Menu::*fptr[3])(int);

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