标签:
函数对象
-使程序设计更加灵活
-能实现函数的inline调用,使性能加速
如果一个对象具有了某个函数的功能,我们称为函数对象
如何使对象具有函数功能呢?
只要为这个对象的操作符()进行重载就行了
换句话说
函数对象就是一个实现了operator()的类
函数对象可以储存数据,可以在函数时作为返回类型
废话不多说,看了代码就明白
#include <iostream> #include <string> using namespace std; class funcobject //定义一个函数对象 { public: funcobject(const char * name):str(name) {} //构造函数,传递一个参数来 bool empty() const { if(str.empty()) return true; } void operator()(char *name) //重载()运算符 { if (!str.empty()) { cout<<str; //打印私有的数据 } cout<<name<<endl; //打印函数传递过来的参数 } private: string str; }; int main() { funcobject obj("Hello"); //定义了一个函数对象类的一个对象,并传递了一个数据 obj(" World"); //调用obj对象的()函数,参数是world //所以这里打印了函数对象中的hello后再打印world obj(" Kitty"); return 0; }
标签:
原文地址:http://www.cnblogs.com/yingzheng-programming/p/5060273.html