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

  • 相关阅读:
    JS身份证验证 根据身份证计算生日 年龄
    手机号码归属地TXT文档数据写入DB
    页面返回 上一页 下一页
    ASP.NET 出错页面处理
    添加外鍵
    WinForm Read Excel
    Winform 中实现省市联动效果
    微信支付之二维码支付(native)
    C#多线程同步(转)
    HTTP超文本传输协议HTTP/1.1中文版(收藏)
  • 原文地址:https://www.cnblogs.com/davidgu/p/4829097.html
Copyright © 2011-2022 走看看