0
点赞
收藏
分享

微信扫一扫

C++学习日记8——函数对象

Just_Esme 2022-03-22 阅读 65
c++

学习视频链接

黑马程序员匠心之作|C++教程从0到1入门编程,学习编程不再难_哔哩哔哩_bilibiliicon-default.png?t=M276https://www.bilibili.com/video/BV1et411b73Z?p=238&spm_id_from=pageDriver

目录

一、函数对象

1.1 函数对象概念

1.2 函数对象使用

二、谓词


一、函数对象

1.1 函数对象概念

1、概念:

重载函数调用操作符的类,其对象常称为函数对象

函数对象使用重载的 () 时,行为类似函数调用,也叫仿函数

2、本质:

函数对象(仿函数)是一个类,不是一个函数

1.2 函数对象使用

1、特点:

函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值

函数对象超出普通函数的概念,函数对象可以有自己的状态

函数对象可以作为参数传递

2、代码

(1) 函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值

#include <iostream>
using namespace std;

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

void test()
{
	MyAdd myadd;
	cout << myadd(10, 10) << endl;
}

int main()
{
	test();
	system("pause");
	return 0;
}

 

(2) 函数对象超出普通函数的概念,函数对象可以有自己的状态

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

class MyPrint
{
public:
	MyPrint()
	{
		this->count = 0;
	}
	void operator()(string test) 
	{
		cout << test << endl;
		count++;
	}
	int count;
};

void test()
{
	MyPrint myprint;
	myprint("hello world");
	cout << "调用次数为:" << myprint.count << endl;
}

int main()
{
	test();
	system("pause");
	return 0;
}

 

(3) 函数对象可以作为参数传递

 

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

class MyPrint
{
public:
	MyPrint()
	{
		this->count = 0;
	}
	void operator()(string test) 
	{
		cout << test << endl;
		count++;
	}
	int count;
};

void doPrint(MyPrint &mp, string test)
{
	mp(test);
}

void test()
{
	MyPrint myprint;
	doPrint(myprint, "Hello C++");
	cout << "调用次数为:" << myprint.count << endl;
}

int main()
{
	test();
	system("pause");
	return 0;
}

 

二、谓词

举报

相关推荐

0 条评论