Chinaunix首页 | 论坛 | 博客
  • 博客访问: 971821
  • 博文数量: 145
  • 博客积分: 1302
  • 博客等级: 中尉
  • 技术积分: 1778
  • 用 户 组: 普通用户
  • 注册时间: 2006-03-07 16:00
文章分类

全部博文(145)

文章存档

2018年(1)

2016年(1)

2015年(6)

2014年(4)

2013年(59)

2012年(32)

2011年(36)

2009年(1)

2007年(2)

2006年(3)

分类: LINUX

2012-12-28 16:51:51

函数指针是通过指向函数的指针间接调用函数。函数指针可以实现对参数类型、参数顺序、返回值都相同的函数进行封装,是多态的一种实现方式。由于类的非静态成员函数中有一个隐形的this指针,因此,类的成员函数的指针和一般函数的指针的表现形式不一样。

1、指向一般函数的指针

函数指针的声明中就包括了函数的参数类型、顺序和返回值,只能把相匹配的函数地址赋值给函数指针。为了封装同类型的函数,可以把函数指针作为通用接口函数的参数,并通过函数指针来间接调用所封装的函数。

下面是一个指向函数的指针使用的例子。

复制代码
#include

/*指向函数的指针*/
typedef int (*pFun)(int, int);

int Max(int a, int b)
{
return a > b ? a : b;
}

int Min(int a, int b)
{
return a < b ? a : b;
}

/*通用接口函数,实现对其他函数的封装*/
int Result(pFun fun, int a, int b)
{
return (*fun)(a, b);
}

void main()
{
int a = 3;
int b = 4;

cout<<"Test function pointer: "< cout<<"The maximum number between a and b is "< cout<<"The minimum number between a and b is "<}
复制代码

 

2、指向类的成员函数的指针

类的静态成员函数采用与一般函数指针相同的调用方式,而受this指针的影响,类的非静态成员函数与一般函数指针是不兼容的。而且,不同类的this指针是不一样的,因此,指向不同类的非静态成员函数的指针也是不兼容的。指向类的非静态成员函数的指针,在声明时就需要添加类名。

下面是一个指向类的成员函数的指针的使用的例子,包括指向静态和非静态成员函数的指针的使用。

复制代码
#include

class CA;

/*指向类的非静态成员函数的指针*/
typedef int (CA::*pClassFun)(int, int);

/*指向一般函数的指针*/
typedef int (*pGeneralFun)(int, int);

class CA
{
public:

int Max(int a, int b)
{
return a > b ? a : b;
}

int Min(int a, int b)
{
return a < b ? a : b;
}

static int Sum(int a, int b)
{
return a + b;
}

/*类内部的接口函数,实现对类的非静态成员函数的封装*/
int Result(pClassFun fun, int a, int b)
{
return (this->*fun)(a, b);
}

};

/*类外部的接口函数,实现对类的非静态成员函数的封装*/
int Result(CA* pA, pClassFun fun, int a, int b)
{
return (pA->*fun)(a, b);
}

/*类外部的接口函数,实现对类的静态成员函数的封装*/
int GeneralResult(pGeneralFun fun, int a, int b)
{
return (*fun)(a, b);
}


void main()
{
CA ca;
int a = 3;
int b = 4;

cout<<"Test nonstatic member function pointer from member function:"< cout<<"The maximum number between a and b is "< cout<<"The minimum number between a and b is "<
cout< cout<<"Test nonstatic member function pointer from external function:"< cout<<"The maximum number between a and b is "< cout<<"The minimum number between a and b is "<
cout< cout<<"Test static member function pointer: "< cout<<"The sum of a and b is "< }
复制代码
阅读(1149) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~