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做函数调用的例子,分别为调用有参数和无参数的函数调用运算符。
浙公网安备 33010602011771号