类和对象 第五部分第六小节:函数调用运算符重载

1、函数调用运算符()可以重载 由于重载后使用方式非常像函数的调用,因此称此为仿函数

代码案例:打印输出仿函数

#include
using namespace std;
class MyPrint
{
public:
	//重载函数调用运算符
	void operator()(string text)
	{
		cout << text << endl;
	}
};
void test01()
{
	//重载的()操作符 也称为仿函数
	MyPrint myFunc;
	myFunc("hello world");
}
int main()
{
	test01();
}

与真函数比较

#include
using namespace std;
//真函数
void test02()
{
	cout << "hello world" << endl;
}

int main()
{
	test02();
}

类和对象 第五部分第六小节:函数调用运算符重载_第1张图片

2.仿函数没有固定写法,非常灵活

代码案例:实现加法运算

#include
using namespace std;
class MyAdd
{
public:
	int operator()(int v1, int v2)
	{
		return v1 + v2;
	}
};
void test02()
{
	MyAdd add;
	int ret = add(10, 10);
	cout << "ret = " << ret << endl;
}

int main()
{
	test02();
}

类和对象 第五部分第六小节:函数调用运算符重载_第2张图片

效果图:

额外:匿名函数对象

#include
using namespace std;
class MyAdd
{
public:
	int operator()(int v1, int v2)
	{
		return v1 + v2;
	}
};
void test02()
{
	MyAdd add;
	int ret = add(10, 10);
	//匿名对象调用  
	cout << "MyAdd()(100,100) = " << MyAdd()(100, 100) << endl;
}

int main()
{
	test02();
}

我们可以直接通过调用匿名函数对象的方式来直接实现函数运算

你可能感兴趣的:(#,C++核心编程,c++,开发语言,程序人生)