C++ 函数对象与函数指针
调用操作符的类,其对象常称为函数对象(function object),即它们是行为类似函数的对象。
简单的说就是重载了()操作符的类
class Add
{
public:
int operator()(int a, int b)
{
return a + b;
}
};
Add add;//add即为函数对象
int b = add(1,2);
函数指针
typedef int (*Add) (int a, int b);
int AddFunc(int a, int b)
{
return a + b;
}
Add add = &AddFunc;//定义一个函数指针
int b = add(1,2);
函数对象和函数指针在使用方式上是完全一样的。
函数对象比函数指针强大的地方就是,函数对象可以携带对象数据,而函数指针则不行。
我们经常希望在调用类成员函数指针的时候也能针对与特定的类对象,把类成员函数指针赋给函数对象保存起来,
这样我们就可以通过调用函数对象来调用特定类对象的成员函数指针。
template<typename T>
class Classfun
{
public:
Classfun(void(T::*f)(const char*), T* o): pFunc(f), pObj(o){}
void operator()(const char* str)
{
(pObj->*pFunc)(str);
}
private:
void(T::*pFunc)(const char*);
T* pObj;
};
class A
{
public:
void print(const char* str)
{ cout << "print" <<str<< "!";}
};
A a;
Classfun<A> call(&A::print, &a); // 保存 a::doIt指针以便调用
call("call"); // 输出 print call !

浙公网安备 33010602011771号