c++STL之函数对象(仿函数)
发布时间:2020-12-16 09:06:47 所属栏目:百科 来源:网络整理
导读:概念: 重载函数调用操作符的类, 其对象被称为函数对象; 函数对象使用重载的()时,行为类似函数调用,也叫仿函数; 本质:函数对象是一个类,不是一个函数; 函数对象使用: - 函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值 - 函数
概念:
本质:函数对象是一个类,不是一个函数; 函数对象使用: - 函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值 #include<iostream> using namespace std; #include <string> class MyAdd { public: int operator()(int v1,int v2) { return v1 + v2; } }; // 1、函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值 void test01() { MyAdd myAdd; cout << myAdd(10,10) <<endl; } 2、函数对象超出普通函数的概念,函数对象可以有自己的状态 MyPrint { : MyPrint() { this->count = 0; } void string test) const { cout << test << endl; this->count++; } int count; 内部自己状态 }; test02() { MyPrint myPrint; myPrint("hello world"); myPrint(); cout << myPrint调用次数为: " << myPrint.count << endl; } 3、函数对象可以作为参数传递 void doPrint(MyPrint & mp,1)"> test) { mp(test); } test03() { MyPrint myPrint; doPrint(myPrint,Hello c++); } main() { test01(); test02(); test03(); system(pause); return ; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |