1. 程式人生 > 其它 >c++ 過載函式呼叫運算子

c++ 過載函式呼叫運算子

過載函式呼叫運算子:

如果類過載了函式呼叫運算子,則可以像使用函式一樣操作類物件。因為這樣的類同時也可以儲存狀態,所以比普通函式更加靈活

 

示例如下:

#include "stdafx.h"
#include "iostream"

using namespace std;

struct NullType
{
};

template <typename T1, typename T2 = NullType>
class Test
{
public:
	Test(T1 a1):a(a1){cout << "Template class" << endl; }
	Test(T1 a1, T2 b1):a(a1), b(b1){ cout << "Template class" << endl; }
	void operator()(){ cout << "Function call operator(No param)" << endl;}
	void operator()(int t){ cout << "Function call operator(has param)" << endl;}

private:
	T1 a;
	T2 b;
};




int main(int argc, char* argv[])
{
	Test<int> obj(5);
	obj();
	obj(6);

	system("pause");

	return 0;
}

  結果:

 

 obj()、obj(6)就是模板類物件obj做函式呼叫的例子,分別為呼叫有引數和無引數的函式呼叫運算子。