How can it be useful to overload the “function call” operator?

后端 未结 7 448
终归单人心
终归单人心 2020-12-02 20:43

I recently discovered that in C++ you can overload the \"function call\" operator, in a strange way in which you have to write two pair of parenthesis to do so:



        
7条回答
  •  一整个雨季
    2020-12-02 21:27

    This can be used to create "functors", objects that act like functions:

    class Multiplier {
    public:
        Multiplier(int m): multiplier(m) {}
        int operator()(int x) { return multiplier * x; }
    private:
        int multiplier;
    };
    
    Multiplier m(5);
    cout << m(4) << endl;
    

    The above prints 20. The Wikipedia article linked above gives more substantial examples.

提交回复
热议问题