首页 > 编程 > C++ > 正文

C++ STL 学习笔记 函数对象

2019-11-06 07:00:57
字体:
来源:转载
供稿:网友

函数对象

c++中函数名后的()称为函数调用运算符。函数调用运算符也可以重载,如果某个类重载了函数调用运算符,则该类的实例就是一个函数对象。函数对象本身并不是很有用,但他们使得算法操作的参数化策略成为可能,使通用性算法变得更加通用(让函数作为参数还可以通过函数指针)

实例

class Add{ double Operator()(double x,double y) { return x+y; }};Add plus; //plus就是一个函数对象cout<<plus(1.2,3.4)<<endl;//通过函数对象调用重载函数cout<<Add() ()(1.2,3.4)<<endl; //Add()会创建一个临时对象

学习代码

#include <iostream>#include <vector>#include <list>#include <algorithm>using namespace std;/*class absInt {};*/ //class和struct都是定义类,struct成员默认属性为publicvoid PRint(double i){ cout << i << " ";}void myforeach(vector<double>::iterator & t1, vector<double>::iterator & t2, void(*fun)(double i))//可以通过函数指针将一个函数作为另一个函数的参数{ while (t1 != t2) { fun(*t1); ++t1; }}struct absInt { //重载操作符() int operator()(int val) { return val < 0 ? -val : val; }};template <typename elementType>void FuncDisplayElement(const elementType & element){ cout << element << " " ;}template <typename elementType>struct DisplayElement { //存储状态 int m_nCount; DisplayElement() { m_nCount = 0; } void operator()(const elementType & element) { ++m_nCount; cout << element << " "; }};int main(){ absInt absObj;//函数对象 int i = -2; unsigned int ui = absObj(i);//通过函数对象调用函数 cout << ui << endl; vector<int> a; for (int i = 0; i < 10; i++) { a.push_back(i); } DisplayElement<int> mResult; mResult = for_each(a.begin(), a.end(), mResult);//把函数对象作为参数传递给另一个函数 cout << endl; cout << "数量" << mResult.m_nCount << endl; list<char> b; for (char c = 'a'; c < 'k'; ++c) { b.push_back(c); } for_each(b.begin(), b.end(), DisplayElement<char>());//DisplayElement<char>()会创建一个临时对象 cout << endl; vector<double> vec = { 76,92,86,74,95 }; cout << "vec里的类容为:" << endl; for_each(vec.begin(), vec.end(), print); cout << "vec里的内容为" << endl; myforeach(vec.begin(), vec.end(), print); getchar(); return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选