zoukankan      html  css  js  c++  java
  • 函数对象

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

    #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

  • 相关阅读:
    python 字符串常用操作
    markdown 基础语法
    网络安全入门的16个基本问题
    Linux中20个crontab例子
    使用python爬取一个网页里表格的内容
    浅谈python的深浅拷贝
    Linux中设置普通用户可以su和sudo
    iptables四表五链
    CentOS7编译安装NFS
    源码安装csvn
  • 原文地址:https://www.cnblogs.com/helloforworld/p/5655378.html
Copyright © 2011-2022 走看看