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

本文介绍了一个使用C++实现的函数指针数组的例子,通过定义一个Card类,该类包含三个成员函数和一个函数指针数组,用于根据用户输入调用不同的成员函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;

 

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值