c++函数对象 c函数对象函数对象又称仿函数Functor是 C 中一个重要的概念。本质上是一个重载了operator()的类或结构体的实例使得该对象可以像函数一样被调用。语法形式Class FunctionObjectType{public:voidoperator(){// 操作语句}}案例#includeiostream#includesetusingnamespacestd;classTestA{public:TestA(string lname,string fname):_fname(fname),_lname(lname){cout\n执行 TestA constructorendl;}stringfirstname()const{return_fname;}stringlastname()const{return_lname;}private:string _fnamenullptr;string _lnamenullptr;};classTestB{public:booloperator()(constTestAa,constTestAb)const{returna.lastname()b.lastname()||(a.lastname()b.lastname()a.firstname()b.firstname());}};intmain(){setTestA,TestBsetbuf;TestAa1(Zhang,San);TestAa2(Li,Si);TestAa3(Wang,Wu);TestAa4(Zhao,Liu);setbuf.insert(a1);setbuf.insert(a2);setbuf.insert(a3);setbuf.insert(a4);for(autox:setbuf){cout x.lastname():x.firstname()endl;}return0;}函数对象优势相比普通函数函数对象有以下优势可以保存状态函数对象是类的实例可以拥有成员变量。编译期优化operator()通常可以被内联展开性能更好。支持泛型编程可以与 STL 算法完美配合。可以有多个重载版本可以重载不同参数类型的operator()。