函数对象本质上在一个类里面重载了()函数调用,导致类创建的对象即有函数属性(可以像函数一样调用)又有类属性(可以当参数传递)

/*概念:
重载函数调用操作符的类,其对象常称为函数对象
函数对象使用重载的()时,行为类似函数调用,也叫仿函数

本质上是在一个类里面重载了()运算符,可以用这个类的对象调用这个函数,这个类具有函数的属性,同时又类的属性

本质:
函数对象(仿函数)是一个类,不是一个函数
4.1.2 函数对象使用
特点:
函数对象在使用时,可以像普通函数那样调用, 可以有参数,可以有返回值
函数对象超出普通函数的概念,函数对象可以有自己的状态
函数对象可以作为参数传递
 *
 */
#include<iostream>
#include <set>
#include <string>
using namespace std;
class MyAdd
{
public:
	int operator()(int v1,int v2)
	{
		return v1+v2;
	}
};
//1、函数对象在使用时,可以像普通函数那样调用, 可以有参数,可以有返回值
void test01()
{
	MyAdd myadd1;
	cout<<myadd1(1,2)<<endl;
}
//2、函数对象可以有自己的状态
class  MyPrint
{
public:
	MyPrint()
	{
		MyCount=0;
	}
	void operator()(string str1)
	{
	cout<<"str1="<<str1<<endl;
		MyCount++;
	}

	int MyCount;//自己内部的状态,统计被调用的次数

};

void test02()
{
	MyPrint myprint1;
	myprint1("helloworld");
	myprint1("helloworld");
	myprint1("helloworld");
	myprint1("helloworld");
	myprint1.operator()("jisuanjicaozuoxitong");
	//重载的运算符本质上是一个名字为(operator+运算符名字)的函数,可以通过对象名.函数名的形式进行调用

	cout<<"myprint调用的次数为"<<myprint1.MyCount<<endl;//5次
}

//函数对象可以作为参数传递,本质上还是一个类,可以创建对象进行传递

void doPrint(MyPrint&mp,string str2)//这里传进来一个MyPrint的函数对象
{
	mp(str2);
}
void test03()
{
	MyPrint myprint03;
	doPrint(myprint03,"hello c++");
}

int main(void)
{
	test01();
	test02();
	test03();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/baixiaolong1993/article/details/89633209
今日推荐