Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1808180
  • 博文数量: 195
  • 博客积分: 4227
  • 博客等级: 上校
  • 技术积分: 2835
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-04 10:39
文章分类

全部博文(195)

文章存档

2013年(1)

2012年(26)

2011年(168)

分类: C/C++

2012-03-19 11:23:20

转载请注明原文链接。

原文链接:http://www.cnblogs.com/xianyunhe/archive/2011/11/27/2265148.html

 

指向一般函数的指针可实现对参数类型、参数顺序、返回值都一样的函数进行封装,指向类的成员函数的指针可实现对一个类中的参数类型、参数顺序、返回值都一样的函数进行封装。对于函数之前,前面已经进行了讨论,该文章的链接为:

http://www.cnblogs.com/xianyunhe/archive/2011/11/26/2264709.html

 

那么,如何能实现对不同类的成员函数进行统一调用呢?我们首先想到的应该会是函数模板和类模板。

下面就一个例子来说明如何实现对不同类的函数成员函数指针的调用。

 

#include

class CA
{
public:

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

class CB
{
public:
float Sum(float a, float b)
{
return a+b;
}
};

template
class CC
{
public:
/*函数指针类型模板*/
typedef ParaType (ClassType::*pClassFun)(ParaType, ParaType);

/*函数指针函数模块*/
ParaType Result(ClassType* pClassType, pClassFun fun, ParaType a, ParaType b)
{
return (pClassType->*fun)(a, b);
}

};

void main()
{
/*测试整型*/
CA ca;
CCint> cc;
int a = 3;
int b = 4;
cout<<"The sum of a and b is "<
/*测试浮点型*/
CB cb;
CCfloat>fcc;
float fa = 3.3f;
float fb = 4.6f;
cout<<"The sum of fa and fb is "<}

 

总结:

1、指针函数模板的使用需要结合类模板和函数模板。

2、类模板中的函数模板的定义必须位于头文件,或者和调用函数位于同一文件,且在调用函数的上方,否则会出现编译错误。

阅读(1277) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~