您的位置:首页 > 编程语言 > C语言/C++

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

2017-03-05 21:43 435 查看
函数对象

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成员默认属性为public

void 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++-函数对象 stl