Parentheses operator overloading

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/dxd_123456/article/details/78066863

Parentheses operator () may be overloaded, overload object can then use the operator parentheses.
Brackets operator can be overloaded non-static member function as a class can not overload friend function and normal function.
The number of parameters contained in the parentheses operator function is not limited, the parameter can not even.
Overload Class format type :: operator () (Table expression);

Here to present a case with heavy-duty brackets parentheses operator


#include <stdio.h>

class Test7
{
public :
    Test7(int a)
    {
        m_a = a;
    }

    void operator()(int num)
    {
        printf("a = %d\n", num);
    }//这里的括号运算符重载的是打印的功能,可以打印出参数

    int operator()(int a, int b)
    {
        return a + b;
    }
//这里的括号运算符重载的是加法的功能,返回和。

private :
    int m_a;
};

int main()
{
    Test7 t(10);
    t(20);     //=====>t.operator()(20)
    printf("() =%d\n",t(10, 20));//=======>t.operator()(10,20)
// t是对象,不是函数,这里t 重载()运算符,所以这样使用
//或许可以称之为伪函数
    return 0;
}

Brackets operator overall not too difficult to understand, is relatively simple.

Guess you like

Origin blog.csdn.net/dxd_123456/article/details/78066863