栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++函数对象

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++函数对象

#include
#include
#include
using namespace std;
//函数对象(仿函数)
//可以像普通函数那样有参数有返回值
//可以有自己的状态
//可以作为参数传递

class Person 
{
public://函数对象这个名称只能使用operator
  int operator()(int v1,int v2){
	  return v1 + v2;
	}
};

void test01() {

	Person person;
	cout << person(10, 10) << endl;

}

class Person1
{
public://函数对象这个名称只能使用operator
	Person1() {
		this->count = 0;
	}
	//可以让他有一个内部状态变成内部属性

	//重载括号
	void operator()(string test) {
		cout << test << endl;
		this->count++;
	}
	int count = 0;


};

void doPrint(Person1 person3,string test) {
	person3(test);//让这个函数可以直接打印test
}

void test02() {

	Person1 person1;
	person1("hello");
	person1("hello");
	person1("hello");
	person1("hello");

	cout << person1.count << endl;
}

//函数对象作为参数传递
void test03() {

	Person1 person12;
	doPrint(person12,"hello");
}

int main() {
	//test02();
	test03();
system("pause");
return 0;

};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/317666.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号