函数对象以及其特点

一、函数对象以及其特点

  1、函数对象:在一个类里面实现()运算符重载;

  2、函数对象的()的执行,很像一个函数//仿函数

  3、函数对象的好处:函数对象属于类对象,能突破函数的概念,能保持调用状态信息,如:for_each算法中,函数对象做函数参数,函数对象做返回值

#include "pch.h"
#include <iostream>
#include"vector"
#include<algorithm>
using namespace std;

//1.函数对象:在一个类里面实现()运算符
template <typename T>
class showElemt
{
public:
    showElemt()
    {
        n = 0;
    }
    void operator()(T &t)
    {
        n++;
        //printN();
        cout << t << " ";

    }
    void printN()
    {
        cout << "n:"<< n << endl;
    }
protected:
    int n;
};

//函数模板
template <typename T>
void funcShowElemt(T &t)
{
    cout << t << endl;
}

void funcShowElemt2(int &t)
{
    cout << t << " ";
}
void test01()
{
    int a = 10;
    showElemt<int> showelemt;
    showelemt(a);//2.函数对象的()的执行,很像一个函数//仿函数
    funcShowElemt<int>(a);
    funcShowElemt2(a);

    return;
}
//3.函数对象的好处:
//函数对象属于类对象,能突破函数的概念,能保持调用状态信息
//如:for_each算法中,函数对象做函数参数,函数对象做返回值
void test02()
{
    vector<int> v1;
    v1.push_back(1);
    v1.push_back(3);
    v1.push_back(5);

    for_each (v1.begin(), v1.end(), showElemt<int>());//匿名函数对象,匿名仿函数
    cout << endl;
    for_each(v1.begin(), v1.end(), funcShowElemt2);//通过回调函数,谁使用for_each,谁去填写回调函数的入口地址
    cout << endl;

    showElemt<int> show1;
    /*_Fn for_each(_InIt _First, _InIt _Last, _Fn _Func)
    {    // perform function for each element [_First, _Last)
    _Adl_verify_range(_First, _Last);
    auto _UFirst = _Get_unwrapped(_First);
    const auto _ULast = _Get_unwrapped(_Last);
    for (; _UFirst != _ULast; ++_UFirst)
        {
        _Func(*_UFirst);
        }
    return (_Func);
    }*/
    show1 = for_each(v1.begin(), v1.end(), show1);//此处函数对象做值传递,不是引用//返回值用匿名对象赋值给show1
    show1.printN();

}
int main()
{
    //test01();
    test02();
    std::cout << "Hello World!
"; 
}
原文地址:https://www.cnblogs.com/jly594761082/p/10597727.html