zoukankan      html  css  js  c++  java
  • c++中的函数对象《未完成》

    头文件:

    #pragma once
    #include<iostream>
    #include<vector>
    using namespace std;
    class Student
    {
    public:
        Student(double hei):height(hei){}
        double getheight() const { return height; }
        ~Student(){}
    private:
        double height;
    };
    
    vector<Student> s;
    for(int i=0;i<5;i++)
        s.???
    // 定义一个函数对象类
    // 用于统计容器中所有Student对象的身高
    class AverageHeight
    {
    public:
        // 构造函数,对类的成员变量作合理的初始化
        AverageHeight()
            : m_nCount(0), m_nTotalHeight(0) {};
        // 定义函数调用操作符“()”,
        // 在其中完成统计的功能
        void operator () (const Student& st)
        {
            // 将当前对象的身高累加到总身高中
            // 这里的m_nTotalHeight记录了上次累加的结果,
             // 这就是函数那失去的记忆
            m_nTotalHeight += st.getheight();
            // 增加已经统计过的Student对象的数目
            ++m_nCount;
        }
        // 接口函数,获得所有统计过的Student对象的平均身高
        float GetAverageHeight()
        {
            if (0 != m_nCount)
                return (float)GetTotal() / GetCount();
        }
        // 获得函数对象类的各个成员变量
        int GetCount() const
        {
            return m_nCount;
        }
        int GetTotal() const
        {
            return m_nTotalHeight;
        }
        // 函数对象类的成员变量,
        // 用来保存函数执行过程中的状态数据
    private:
        int m_nCount;  // 记录已经统计过的对象的数目 
        int m_nTotalHeight;  // 记录已经统计过的身高总和
    };
    View Code

    源文件:

    #include"wuyong.h"
    using namespace std;
    int main()
    {
        // 创建函数对象
        AverageHeight ah;
        // 将函数对象应用到for_each()算法中以完成统计
        ah = for_each(vecStu.begin(), vecStu.end(), ah);
        // 从函数对象中获取它的记忆作为结果输出
        cout << ah.GetCount() << "个学生的平均身高是:"
            << ah.GetAverageHeight() << endl;
        system("pause");
        return 0;
    }
    View Code
  • 相关阅读:
    负数之美
    css重设
    编码问题
    wed的各种前端打印方法(3)CSS
    表单
    学习前端心得
    去除input,a,按键链接时出现的虚线方法
    加载事件js代码
    深入C#数据类型
    查找
  • 原文地址:https://www.cnblogs.com/yibeimingyue/p/10556763.html
Copyright © 2011-2022 走看看