函数对象

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

#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

转载于:https://www.cnblogs.com/helloforworld/p/5655378.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值