函数对象

若一个类重载了运算符“()”,则该类的对象就成为函数对象。函数对象可以用于标准库算法。函数对象和函数指针很相似,但也有区别。当函数对象使用模板时可以赋值给函数指针。

#include <iostream
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;

int sumsquares(int total, int value)
{
    return (total += value*value);
}

template <class T>
void printValue(T first, T last)
{
    for (; first != last; first++)
    {
        cout << *(first) << " ";
    }
    cout << endl;
}

template <class T>
class sumPower
{
private:
    int power;
public:
    sumPower(int power) :power(power) {};
    const T operator()(const T & total, const T &value)
    {
        T v = value;
        cout << "the function is called" << endl;
        for (int i = 1; i < power; i++)
            v *= value;
        return (total + v);
    }
};

int main()
{
    const int size = 3;
    int a[] = { 1,2,3 };
    vector<int> a1(a, a + size);
    printValue(a1.begin(),a1.end());
    int result = accumulate(a1.begin(), a1.end(), 0,sumsquares);
    cout << "1)" << "平方和" << result << endl;
    sumPower<int> b(4);
    //每次调用它的函数形参时,它都使用相应的调用操作符
    result = accumulate(a1.begin(), a1.end(), 0, sumPower<int>(3));
    cout << "2)" << "立方和" << result << endl;
    return 0;
}

 

函数运行结果:

 

 

 参考链接:

https://www.coursera.org/learn/cpp-chengxu-sheji

posted @ 2016-07-09 10:43  helloforworld  阅读(203)  评论(0编辑  收藏  举报