函数对象¶
- 功能:函数对象可以是一个类对象像函数调用一样可以执行
1 实现原理¶
通过在类中实现操作符()
来使类对象可以像函数般执行
2 示例¶
//函数对象
#include <iostream>
#include<string>
using namespace std;
#if 1
class FUNOBJ
{
public:
FUNOBJ()=default;
~FUNOBJ()=default;
int operator ()(const int& x1, const int& x2)
{
std::cout << to_string(x1) << "+" << to_string(x2) << "= " << x1 + x2 << std::endl;
return x1 + x2;
}
private:
};
int main()
{
FUNOBJ funObj;
funObj(1, 2);
funObj.operator()(1, 2);
FUNOBJ()(3, 4);
FUNOBJ{}(5, 6);
FUNOBJ().operator()(1, 2);
}
#endif // 1