C++类成员指针指向成员函数

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-30 20:40   52   0

对于实现功能类似的函数,通常可以使用switch case语法调用函数,这样做显得代码比较长,不简洁,可以通过定义函数指针的形式实现,具体代码如下所示:

#include <iostream>

using namespace std;

class base
{
public :
void func1(){cout << "func1" << endl ;}
void func2(){cout << "func2" << endl ;}
void func3(){cout << "func3" << endl ;}
void func4(){cout << "func4" << endl ;}
void func5(){cout << "func5" << endl ;}
void func6(){cout << "func6" << endl ;}
void (base::*func[6])() = {func1,func2,func3,func4,func5,func6};

void disFunc(int n){if(n > 5) return ;(this->*func[n])();}
};

int main()
{
base ba ;
ba.disFunc(3) ;
return 0;
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP