VC++ 类成员函数指针导出与导入
一、导入外来函数指针
定义一个类,类中有几个函数成员完成相似的功能,根据调用者选的模式对相应的函数进行调用 在Funtion()函数下如果按下面的代码调用的话,由于这个Funtion()频繁调用(成千上万次).如果每次都进行判断性能会降低很多.所以准备用类成员函数代替下面的段代码.
复制代码
switch(iFlag)
{
case 1:
Fun1();
break;
case 2:
Fun2();
break;
case 3:
Fun3();
break;
}
复制代码
在类中定义
typedef void (BaseClass::*FUN)();
然后声明函数成员
FUN m_fun;
在构造函数中根据相应的模式进行指针赋值
复制代码
switch(iFlag)
{
case 1:
m_fun=Fun1;
break;
case 2:
m_fun=Fun2;
break;
case 3:
m_fun=Fun3;
break;
}
复制代码
在调用出直接用类成员函数指针调用.却报了error C2064: term does not evaluate to a function这个错误
Funtion()
{
m_fun();
}
呵呵…其实原因很简单…成员函数指针和类成员函数指针的区别就是累成员函数会有一个this指针需要 加上这个指针上述代码改为下面的形式…ok.编译成功…
Funtion()
{
(this->*m_fun)();
}
二、导出类成员函数指针:
导出类成员函数指针常用的方式是导出静态成员函数指针,但是局限性表较大,以下整理了非静态成员函数指针的导出。
#include “stdafx.h”
//std::function需要此头文件
#include
#include
#include
//std::find需要此头文件
#include
using namespace std;
/********************************************
First类和Second相当于两个观察者, 他们两个没有继承结构
First类和Second类的更新函数原型相同,函数名不必相同
********************************************/
class First
{
public:
int Add1(int a, int b) //更新函数
{
return a + b;
}
};
class Second
{
public:
int Add2(int a, int b) //更新函数,
{
return a + b;
}
};
typedef std::function<int(int, int)> PAdd;
class CTest
{
public:
void run(PAdd func)
{
func(10, 20);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
First objFirst;
Second objSecond;
CTest obj;
PAdd pAdd1 = std::bind(&First::Add1, &objFirst, std::placeholders::_1, std::placeholders::_2);
PAdd pAdd2 = std::bind(&Second::Add2, &objSecond, std::placeholders::_1, std::placeholders::_2);
obj.run(pAdd1);
obj.run(pAdd2);
}