C++中使用函数指针有几种方式,这里只是介绍一下其中的一种,这种方法是在C++类中使用函数指针。(VC中实现)
首先,在头文件类的定义下面加入这样的语句(比如类名为CTestpFunc)
typedef int (CTestpFunc::*PTRFUN[4])(int,int);
PTRFUN pfun;
上面的typedef 中加入的为类名表示要使用的函数指针属于该类。(这里使用的就是函数指针数组)
现在给出头文件的内容:
#ifndef _TESTPFUNC_H
#define _TESTPFUNC_H
#include "iostream"
using namespace std;
class CTestpFunc
{
public:
int one;
int two;
public:
CTestpFunc();
~CTestpFunc();
int Sub(int one,int two); //两数相减
int Add(int one,int two); //相加
int Div(int one,int two); //相除
int Mul(int one,int two); //相乘
};
typedef int (CTestpFunc::*PTRFUN[4])(int,int); //函数指针,并注明属于类CTestpFunc类
PTRFUN pfun;
#endif
//下面是CPP文件:
/
#include "testpfunc.h"
CTestpFunc::CTestpFunc()
{
this->one=0;
this->two=1;
}
CTestpFunc::~CTestpFunc()
{
}
/*
* 函数功能:两数相加
* 参数描述:
*/
int CTestpFunc::Add(int one,int two)
{
return one+two;
}
/*
* 函数功能:两数相减
* 参数描述:
*/
int CTestpFunc::Sub(int one,int two)
{
return one-two;
}
/*
* 函数功能:两数相除
* 参数描述:
*/
int CTestpFunc::Div(int one,int two)
{
if ( 0 ==two )
{
cout<<"被除数不能为0!/n";
return 0;
}
else
{
return one/two;
}
}
/*
* 函数功能:两书相乘
* 参数描述:
*/
int CTestpFunc::Mul(int one,int two)
{
return one*two;
}
int main(int agrc,char* agrv[])
{
int one,two;
cout<<"请输入两个整数:";
cin>>one>>two;
CTestpFunc* testfunapp=new CTestpFunc; //这里不用new也可以,直接CTestpFunc testfunapp;
pfun[0]=testfunapp->Add; //使用函数指针
pfun[1]=testfunapp->Sub;
pfun[2]=testfunapp->Div;
pfun[3]=testfunapp->Mul;
for (int index=0; index<4; ++index)
{
int result;
result=(testfunapp->*pfun[index])(one,two); //通使用函数指针,这里一定要使用()把testfunapp.*pfun[index]括起来
switch(index)
{
case 0:
cout<<"相加的结果为:"<<result<<"/n";
break;
case 1:
cout<<"相减的结果为:"<<result<<"/n";
break;
case 2:
if(0!=two)
{
cout<<"相除的结果为:"<<result<<"/n";
}
break;
case 3:
cout<<"相乘的结果为:"<<result<<"/n/n";
default:
break;
}
}
return 1;
}
上面的使用也可以这样:CTestpFunc testfunapp;
然后使用 (testfunapp.*pfun[index])(one,two)
无论是哪种,都要用括号敬爱那个其括起来,即:(testfunapp.*pfun[index]) 或者 (testfunapp->*pfun[index])
不然会出现提示:“term does not evaluate to a function”的错误。