c++STL之函数对象仿函数

概念:

本质:函数对象是一个类,不是一个函数

函数对象使用:

- 函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
- 函数对象超出普通函数的概念,函数对象可以有自己的状态
- 函数对象可以作为参数传递

#include<iostream>
using namespace std;
#include <string>


class MyAdd
{
public:
    int operator()(int v1,int v2)
    {
        return v1 + v2;
    }

};

// 1、函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
void test01()
{
    MyAdd myAdd;
    cout <<  myAdd(10,10) <<endl;
}


2、函数对象超出普通函数的概念,函数对象可以有自己的状态
 MyPrint
{
:
    MyPrint()
    {
        this->count = 0;
    }
    void string test) const
    {
        cout << test << endl;
        this->count++;
    }

    int count;  内部自己状态
};

 test02()
{
    MyPrint myPrint;
    myPrint("hello world");
    myPrint();

    cout << myPrint调用次数为: " << myPrint.count << endl;
}

3、函数对象可以作为参数传递
void doPrint(MyPrint & mp,1)"> test)
{
    mp(test);
}

 test03()
{
    MyPrint myPrint;
    doPrint(myPrint,Hello c++);
}

 main() {

    test01();

    test02();

    test03();

    system(pause);

    return ;
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...