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

  • 相关阅读:
    PHP Socket服务器搭建和测试
    Linux socket编程示例
    深入浅出讲解:php的socket通信
    Linux系统下/tmp目录文件重启后自动删除
    斐讯K2路由器刷不死固件+openwrt
    php ddos 安全处理代码
    windows通过ftp下载linux文件
    win7 重启dns
    hostname -f 失败解决办法
    ERROR 2003 (HY000): Can't connect to MySQL server on "" (113)
  • 原文地址:https://www.cnblogs.com/davidgu/p/4829097.html
Copyright © 2011-2022 走看看