当前位置:编程学习 > C/C++ >>

函数指针

1.简要介绍
 
2.使用示例
函数指针的一般用法:
[cpp]  
#include "stdafx.h"  
  
typedef int (*AddCommFunc)(const int &a, const int &b);  
  
int AddRight(const int &a, const int &b)  
{  
    return (a + b);  
}  
  
int AddError(const int &a, const int &b)  
{  
    return (a - b);  
}  
  
int _tmain(int argc, _TCHAR* argv[])  
{  
    AddCommFunc pfn = NULL;  
    pfn = AddRight;  
    int result = pfn(1, 2);  
    return 0;  
}  
 
3.问题
如果函数指针指向的是类的成员函数,怎么处理
[cpp]  
#include "stdafx.h"  
  
class CalcClass;  
typedef int (CalcClass::*AddCommFunc)(const int &a, const int &b);  
  
class CalcClass  
{  
public:  
    int AddRight(const int &a, const int &b)  
    {  
        return (a + b);  
    }  
  
    int AddError(const int &a, const int &b)  
    {  
        return (a - b);  
    }  
protected:  
private:  
};  
  
  
  
  
int _tmain(int argc, _TCHAR* argv[])  
{  
  
    CalcClass *pC = new CalcClass;  
    AddCommFunc pf= &CalcClass::AddRight;  
  
    int result = (pC->*pf)(1, 2);  
  
    return 0;  
}  
 
在定义函数指针的时候要加上类限定符
在调用函数指针的时候还是要加上*
 
补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,