运算符重载

59 阅读1分钟

函数调用运算符重载

  • 函数调用运算符()也可以重载
  • 由于重载后的使用的方式非常像函数的调用,因此称仿函数
  • 仿函数没有固定写法,非常灵活

class MyFunc{
    public:
        void operator()(std::string str){
           std::cout << str << std::endl;
        }

        int operator()(int a, int b){
            return a + b;
        }
    int num;
    std::string name;
};

int main(){
    MyFunc obj;
    obj("Test MyFunc......");
    int sum = obj(1,2);
    std::cout << "Two digitals's sum is " << sum << std::endl;
}