分享

类成员函数的函数指针与返回值为函数指针的函数

 quasiceo 2014-01-17
分类: c++ 2013-02-26 17:27 257人阅读 评论(0) 收藏 举报

首先我们先看类的定义;


  1.   
  1.   
  1.   
  1. #include <iostream>  
  2. using namespace std;  
  3. class FunctionPoint  
  4. {  
  5. public:  
  6.     FunctionPoint(int s);  
  7.     ~FunctionPoint(void);  
  8.   
  9.   
  10.     static FunctionPoint* pFunctionPoint;  
  11.   
  12.   
  13.     static int FunctionName1(int a,int b);  
  14.     static int FunctionName2(int a,int b);  
  15.   
  16.   
  17.     int m_s;  
  18. };  



接下来我们可以查看类的实现:

  1. #include "FunctionPoint.h"  
  2. FunctionPoint* FunctionPoint::pFunctionPoint=nullptr;  
  3.   
  4. FunctionPoint::FunctionPoint(int s)  
  5. {  
  6.     pFunctionPoint =this;  
  7.     m_s = s;  
  8. }  
  9.   
  10.   
  11. FunctionPoint::~FunctionPoint(void)  
  12. {  
  13. }  
  14.   
  15. int FunctionPoint::FunctionName1(int a,int b)  
  16. {  
  17.     cout<<a<<""<<b<<endl;  
  18.     cout<<pFunctionPoint->m_s<<endl;  
  19.     return 0;  
  20. }  
  21. int FunctionPoint::FunctionName2(int a,int b)  
  22. {  
  23.     cout<<pFunctionPoint->m_s<<endl;  
  24.     cout<<b<<""<<a<<endl;  
  25.     return 0;  
  26. }  


最后我们实现如何使用:
  1. #include "FunctionPoint.h"  
  2.   
  3.   
  4. int (*opp(FunctionPoint m_class,int FunctionIndex))(int a, int b)  
  5. {  
  6.     if(FunctionIndex == 1)  
  7.     {  
  8.         return m_class.FunctionName1;  
  9.     }  
  10.     else  
  11.     {  
  12.         return m_class.FunctionName2;  
  13.     }  
  14. }  
  15.   
  16. int main()  
  17. {  
  18.     FunctionPoint fp1(2);  
  19.     printf("类的函数指针:%d, %d/n", opp(fp1,1)(3, 4), opp(fp1,2)(3, 4));  
  20.     FunctionPoint fp2(7);  
  21.     printf("类的函数指针:%d, %d/n", opp(fp1,1)(3, 4), opp(fp1,2)(3, 4));  
  22.     printf("类的函数指针:%d, %d/n", opp(fp2,1)(3, 4), opp(fp2,2)(3, 4));  
  23.     system("pause");  
  24.     return 0;  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多