006函數調用運算符重載--仿函數

/*
函數調用運算符 () 也可以重載
由於重載後使用的方式非常像函數的調用,因此稱爲仿函數
仿函數沒有固定寫法,非常靈活
*/
#include<iostream>
#include<string>
using namespace std;


class MyPrint
{
public:
	void operator()(string text)
	{
		cout << text << endl;
	}
};

class MyAdd
{
public:
	int operator()(int val1, int val2)
	{
		return val1 + val2;
	}
};

void playObject()
{
	//重載()運算符,可以像函數一樣調用,也不用使用.運算符
	MyPrint myprint;
	myprint.operator()("計算機組成原理");
	myprint("計算機操作系統");


	MyAdd myadd;
	int sum = myadd.operator()(10, 20);
	cout << "sum=" << sum << endl;
	//可以當作匿名函數進行調用
	cout << myadd(100, 200) << endl;
}


int main(void)
{
	playObject();

	system("pause");
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章