VC驿站

 找回密码
 加入驿站

QQ登录

只需一步,快速开始

搜索
查看: 519|回复: 1

[已解决]类内函数指针如何调用

[复制链接]
93_avatar_middle
最佳答案
0 
在线会员 发表于 2020-6-21 22:10:35 | 显示全部楼层 |阅读模式

class::test1(int a)

class::test2(int a)

class::test3(int a)



定义类函数指针数组

void(class::func)(int) = {&class::test1,&class::test2,&class::test3}

如何调用指针函数 或还有什么办法定义和调用类指针函数
最佳答案
70_avatar_small
2020-6-22 09:20:02
不知道你想要的是不是这种效果
  1. class A;
  2. typedef  int (A::* pAFunc)(int x);
  3. class A {

  4. private:
  5.     int val;
  6. public:
  7.     A(int x) :val(x) {};

  8.     int func1(int x) {
  9.         cout << val + 1 << endl;
  10.         return val + 1;
  11.     }
  12.     int func2(int x) {
  13.         cout << val + 2 << endl;
  14.         return val + 2;
  15.     }
  16.     int FuncRun(pAFunc  func,int x) {
  17.         return (this->*func)(x);
  18.     }
  19. };
  20. int main() {
  21.     A a(10);
  22.     pAFunc funcArray[2];
  23.     funcArray[0] = &A::func1;
  24.     funcArray[1] = &A::func2;
  25.     a.FuncRun(funcArray[0], 99);
  26.     a.FuncRun(funcArray[1], 99);
  27.     return 0;
  28. }
复制代码




上一篇:想请问一下C++的new有没有类似realloc的功能
下一篇:GetBitmap报错
70_avatar_middle
最佳答案
49 
在线会员 发表于 2020-6-22 09:20:02 | 显示全部楼层    本楼为最佳答案   
bestAnswer
不知道你想要的是不是这种效果
  1. class A;
  2. typedef  int (A::* pAFunc)(int x);
  3. class A {

  4. private:
  5.     int val;
  6. public:
  7.     A(int x) :val(x) {};

  8.     int func1(int x) {
  9.         cout << val + 1 << endl;
  10.         return val + 1;
  11.     }
  12.     int func2(int x) {
  13.         cout << val + 2 << endl;
  14.         return val + 2;
  15.     }
  16.     int FuncRun(pAFunc  func,int x) {
  17.         return (this->*func)(x);
  18.     }
  19. };
  20. int main() {
  21.     A a(10);
  22.     pAFunc funcArray[2];
  23.     funcArray[0] = &A::func1;
  24.     funcArray[1] = &A::func2;
  25.     a.FuncRun(funcArray[0], 99);
  26.     a.FuncRun(funcArray[1], 99);
  27.     return 0;
  28. }
复制代码
您需要登录后才可以回帖 登录 | 加入驿站 qq_login

本版积分规则

×【发帖 友情提示】
1、请回复有意义的内容,请勿恶意灌水;
2、纯数字、字母、表情等无意义的内容系统将自动删除;
3、若正常回复后帖子被自动删除,为系统误删的情况,请重新回复其他正常内容或等待管理员审核通过后会自动发布;
4、感谢您对VC驿站一如既往的支持,谢谢合作!

关闭

站长提醒上一条 /2 下一条

QQ|小黑屋|手机版|VC驿站 ( 辽ICP备09019393号-4 )|网站地图wx_jqr

GMT+8, 2023-3-23 14:32

Powered by CcTry.CoM

© 2009-2021 cctry.com

快速回复 返回顶部 返回列表