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

函数对象

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值