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

 

posted on 2019-03-19 10:01  一杯明月  阅读(148)  评论(0编辑  收藏  举报