zoukankan      html  css  js  c++  java
  • C++ 11

    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 ----------------

  • 相关阅读:
    3.10 Go Map哈希表
    3.9 Go Slice切片
    3.8 Go Array数组
    3.7 Go指针
    3.6 Go String型
    3.5 Go布尔型
    3.4 Go字符型
    3.3 Go浮点型
    3.2 Go整数类型
    3.1Go变量
  • 原文地址:https://www.cnblogs.com/davidgu/p/4829097.html
Copyright © 2011-2022 走看看