首页 > 技术文章 > C++程序设计方法2:函数运算符重载

hujianglang 2017-03-27 21:57 原文

函数运算符()重载

函数运算符()也能重载,它使得对象看上去像是一个函数名

ReturnType operator() (Parameters)

{

......

}

ClassName Obj;

Obj(real_parameters);

//->obj.operator() (real_parameters);

#include <iostream>
using namespace std;

class Test
{
public:
    int operator() (int a, int b)
    {
        cout << "operator() called." << a << " " << b << endl;
        return a + b;
    }
};

int main()
{
    Test sum;
    int s = sum(3, 4);//sum对象看上去像是一个函数,故也成为“函数对象”
    cout << "a + b = " << s << endl;
    return 0;
}

 

#include <iostream>
using namespace std;

class Less
{
    int thres_;
public:
    Less(int th) :thres_(th) {}
    bool operator() (int);
};

bool Less::operator() (int value)
{
    return (value < thres_);
}

void Filter(int *array, int num, Less fn)
{
    for (int i = 0; i < num; i++)
    {
        if (fn(array[i]))
            cout << array[i] << " ";
    }
    cout << endl;
}

int main()
{
    int array[5] = { 1,-4,10,0,-1 };
    int thres;
    cout << "thres:";
    cin >> thres;
    Less less_than(thres);
    Filter(array, 5, less_than);
    return 0;
}

 

推荐阅读