在c++类中使用函数指针数组

   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”的错误。

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值