C++ 11 - STL - 函数对象(Function Object) (上)

1. 定义

在STL中,可以把函数传递给算法,也可以把函数对象传递给算法。

那么,什么是函数对象呢?

我们来看下它的声明:

class X
{
public:
  // define function call operator
  return-value operator() (arguments) const;
  ...
}

你可以这样调用:
X fo;

...

fo(arg1, arg2);

我们来看个简单的打印的例子

PrintInt.h

#ifndef        Print_Int_H_
#define        Print_Int_H_

#include <iostream>
using namespace std;
class PrintInt 
{
public:
    void operator() (int elem) const 
    {
        cout << elem << ' ';
    }
};

#endif

FuncObjectTest.h

#ifndef        Stl_Alg_Func_Object_Test_H_
#define        Stl_Alg_Func_Object_Test_H_

#include "../../TestBase.h"

class FuncObjectTest : public TestBase
{
public:
    FuncObjectTest(const string &c, const string &d) : TestBase(c, d) { }
    void run();
private:
    void printFuncObject();
};

#endif

FuncObjectTest.cpp

#include <vector>
#include <algorithm>
#include <iostream>
#include "FuncObjectTest.h"
#include "../../Core/PrintInt.h"

using namespace std;

void FuncObjectTest::printFuncObject()
{
    vector<int> coll;

    // insert elements from 1 to 9
    for (int i = 1; i <= 9; ++i) {
        coll.push_back(i);
    }

    // print all elements
    for_each(coll.cbegin(), coll.cend(),  // range
        PrintInt());                 // operation
    cout << endl;
}

void FuncObjectTest::run()
{
    printStart("printFuncObject()");
    printFuncObject();
    printEnd("printFuncObject()");
}

运行结果:

---------------- printFuncObject(): Run Start ----------------
1 2 3 4 5 6 7 8 9
---------------- printFuncObject(): Run End ----------------

转载于:https://www.cnblogs.com/davidgu/p/4829097.html

猜你喜欢

转载自blog.csdn.net/weixin_34195142/article/details/93802623
今日推荐