STL-関数オブジェクト

STL-関数オブジェクト

4.1関数オブジェクト
4.1.1関数オブジェクトの概念

オーバーロードされた関数呼び出し演算子のクラス。そのオブジェクトはしばしば関数オブジェクトと呼ばれます。

関数オブジェクトがオーバーロードされた()を使用する場合、動作は関数呼び出しに似ており、関数とも呼ばれます

本質:
関数オブジェクト(関数)はクラスであり、関数ではありません。
関数オブジェクトが使用されます

機能:
関数オブジェクトが使用されている場合、通常の関数のように呼び出すことができ、パラメーターを持ち、戻り値を持つことができます

関数オブジェクトは通常の関数の概念を超えており、関数オブジェクトは独自の状態を持つことができます

関数オブジェクトはパラメーターとして渡すことができます

コード例:

#include<iostream>
#include<string>
using namespace std;
//函数对象(仿函数)
class MyAdd
{
    
    
public:
       int operator()(int v1, int v2)
       {
    
    
              return v1 + v2;
       }
};
//1.函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
void test01()
{
    
    
       MyAdd myAdd;
       cout << myAdd(10, 10) << endl;
}
//2.函数对象超出普通函数概念,函数对象可以有自己的状态
class Myprint
{
    
    
public:
       Myprint()
       {
    
    
              this->count = 0;
       }
       void operator()(string test)
       {
    
    
              cout << test << endl;
              this->count++;
       }
       int count;    //内部自己状态
};
void test02()
{
    
    
       Myprint myPrint;
       myPrint("Hello world");
       myPrint("Hello world");
       cout << "myPrint调用次数为:" << myPrint.count << endl;
}
//3.函数对象可以作为参数传递
void doPrint(Myprint &mp, string test)
{
    
    
       mp(test);
}
void test03()
{
    
    
       Myprint myPrint;
       doPrint(myPrint, "Hello C++");
}
int main()
{
    
    
       test01();
       test02();
       test03();
       system("pause");
       return 0;
}

おすすめ

転載: blog.csdn.net/gyqailxj/article/details/115057425