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

简介: 1. 定义 在STL中,可以把函数传递给算法,也可以把函数对象传递给算法。 那么,什么是函数对象呢? 我们来看下它的声明: class X { public: // define function call operator return-value operator() (arguments) const; .

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

 

目录
相关文章
|
4天前
|
存储 编译器 C语言
c++的学习之路:5、类和对象(1)
c++的学习之路:5、类和对象(1)
19 0
|
4天前
|
C++
c++的学习之路:7、类和对象(3)
c++的学习之路:7、类和对象(3)
19 0
|
3天前
|
编译器 C++
【C++基础(八)】类和对象(下)--初始化列表,友元,匿名对象
【C++基础(八)】类和对象(下)--初始化列表,友元,匿名对象
|
9天前
|
编译器 C++
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(中)——“C++”
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(中)——“C++”
|
9天前
|
存储 编译器 C++
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(上)——“C++”
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(上)——“C++”
|
10天前
|
C++
【C++成长记】C++入门 | 类和对象(下) |Static成员、 友元
【C++成长记】C++入门 | 类和对象(下) |Static成员、 友元
|
10天前
|
存储 编译器 C++
【C++成长记】C++入门 | 类和对象(中) |拷贝构造函数、赋值运算符重载、const成员函数、 取地址及const取地址操作符重载
【C++成长记】C++入门 | 类和对象(中) |拷贝构造函数、赋值运算符重载、const成员函数、 取地址及const取地址操作符重载
|
14天前
|
编译器 C语言 C++
【C++初阶(九)】C++模版(初阶)----函数模版与类模版
【C++初阶(九)】C++模版(初阶)----函数模版与类模版
18 0
|
16天前
|
存储 编译器 C语言
C++类与对象
C++类与对象
16 0
|
25天前
|
存储 缓存 C++
C++链表常用的函数编写(增查删改)内附完整程序
C++链表常用的函数编写(增查删改)内附完整程序

热门文章

最新文章