c++ function call method

The main function of the functor is to be used with the STL algorithm, and the use of the functor alone is relatively rare.
The name used for functors in the C++ standard is function objects. Functors are mainly used in algorithms in STL. Although function pointers can also be used as algorithm parameters, function pointers cannot meet STL's requirements for abstraction, nor can they meet the requirements of software building blocks – function pointers cannot be matched with other STL components , Produce more flexible changes. The essence of a functor is that the class overloads an operator() to create an object that behaves like a function.

For a class with overloaded () operator, a similar function call process can be implemented, so it is called a functor. In fact, the functor only occupies 1 byte, because there are no data members inside, it is just an overloaded method. In fact, similar functions can be achieved by passing function pointers, but in order to cooperate with STL internal use, he provides the features of functors.

See the code for the calling method:

struct MyPlus{
    
    
    int operator()(const int &a , const int &b) const{
    
    
        return a + b;
    }
};

int main()
{
    
    
    MyPlus a;
    cout << MyPlus()(1,2) << endl;//1、通过产生临时对象调用重载运算符
    cout << a.operator()(1,2) << endl;//2、通过对象显示调用重载运算符
    cout << a(1,2) << endl;//3、通过对象类似函数调用 隐示地调用重载运算符
    return 0;
}

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_33898609/article/details/105970094