函数指针数组的应用,但在类内作为成员使用,需要特殊处理,指针类型要匹配

时间:2022-03-09 15:29:26

#include <iostream.h>

class Card
{
public:
        Card();
 
        void fun1();
        void fun2();
        void fun3();
        void getFunction(int);

private:
        void (Card::*menu[3]) ();       // define a function pointer array


};

Card::Card()
{
        menu[0] = &Card::fun1;
        menu[1] = &Card::fun2;
        menu[2] = &Card::fun3;
}

void Card::getFunction(int choice)
{
        (this->*menu[choice]) ();
}

void Card::fun1()

        cout << "fun1 output." << endl;
}

void Card::fun2()
{
        cout << "fun2 output." << endl;
}

void Card::fun3()
{
        cout << "fun3 output." << endl;
}


int main(int argc, char *args[])

        Card card;

        int choice;
        cout << "Enter a number from 0 to 2:";
        cin >> choice;

        while ( choice >= 0 && choice < 3 )
        {
               card.getFunction(choice);
               cout << "Enter a number from 0 to 2:";
               cin >> choice; 
        }

        return 0;

 

}